2016-07-11 20 views
1

例如,我有一個4×4矩陣提取元件從一個矩陣矢量

A = [1, 2, 3, 4; 
     2, 1, 4, 3; 
     1, 2, 4, 3; 
     4, 1, 2, 3;]; 

對於每一行,我想提取1和3之間的元件(假設矩陣總是有一些元件1和3之間,1總是在3)之前。例如,返回等的細胞[{2},{4},{2,4},{2}],或甚至更好的與基質

B= [0, 1, 0, 0; 
    0, 0, 0, 1; 
    0, 1, 0, 1; 
    0, 1, 0, 0;]; 

現在我做一個循環的每一行,找到,則設置在它們之間的索引是零,即,在1和3中的索引

B = zeros(4,4); 
    for i = 1 : size(A,1) 
     ind1 = find(A(i,:) ==1); 
     ind2 = find(A(i,:) ==3); 
     B(i, A(i,ind1+1:ind2-1)) = 1; 
    end 

任何生成該矩陣B或者只是細胞更簡單的方法?任何建議表示讚賞。

+1

我不udnerstand如何定義之間。你的意思是你可以找到'[1 2 3]'的地方?我不明白'B'的第三行。 –

+1

也是第四個我會說 – shamalaia

+2

GameOfThrows的B似乎對我來說是正確的 – shamalaia

回答

4

好吧,這可能不是一個簡單的解決方案,但它確實消除環路,所以應該更快的是計算:

的想法是不是嘗試查找1和3之間的號碼,並將其設置爲1,我要尋找的數字外1和3,設置那些以0:

B=zeros(4,4); 
B(A == 1) = 1; 
B(A == 3) = 1; 
C = cumsum(B')'; 
B(C>=2) =1; 
B(C< 1) =1; 

%finally you want to invert this: 
B = (B-1)*-1; 

>> B = 

0  1  0  0 
0  0  1  0 
0  1  1  0 
0  0  1  0 

==========你的第二個編輯後本部分適用於======= ===

D = A.*B % this seems to be the cell indexes you are after? 

D = 

0  2  0  0 
0  0  4  0 
0  2  4  0 
0  0  2  0 

E = zeros(4,4); 
for t = 1:size(A,1) 
    E(t,D(t,D(t,:)>0)) = 1; %This re-applies the index numbers and create a new index matrix through a loop........ 
    %or you can use E(t,D(t,~~D(t,:))) = 1 to same effect, Thanks to @Dev-iL 
end 


>> E = 

0  1  0  0 
0  0  0  1 
0  1  0  1 
0  1  0  0 

這將爲您提供A和1之間元素的索引,然後您可以使用邏輯索引來查找所需的單元格編號。

+1

但是這個B不同於OP B –

+0

@AnderBiguri,因爲他在最後做了A. * B,讓我把它放進去。 – GameOfThrows

+1

但是... 。這與OP在他的帖子中顯示的內容仍然不同,究竟是什麼? (它已被編輯,我現在看到) –

2

我的解決方案與已經提出的方案沒什麼區別,但它有一個bsxfun,所以我說 - 爲什麼不呢? :)

function B = q38307616 

A = [1, 2, 3, 4; 
    2, 1, 4, 3; 
    1, 2, 4, 3; 
    4, 1, 2, 3;]; 

At = A.'; 

tmp = arrayfun(@colon,find(At==1)+1,find(At==3)-1,'UniformOutput',false); 
% [tmp{:}] gives us the indices of the elements we should be considering 

B = 0*A; %preallocation 
for ind1 = 1: numel(tmp) 
    B(ind1,:) = sum(bsxfun(@eq,At(tmp{ind1}).',1:4),1); %1:4 are the allowable values 
end 

「紅利」:獲得每一行,這是相同的1和3之間的元素的邏輯地圖GameOfThrows'B的另一種方式,是通過:

tmp2 = reshape(full(sparse(~~[tmp{:}],[tmp{:}],~~[tmp{:}],1,numel(A)).'),size(A));