2015-06-30 11 views
0

假設輸入是以下矩陣,對於給定的(0,1)矢量,返回所有(1,0)對所述指數該矩陣的每一行中的matlab

[0,1,0,1; 
1,0,1,0] 

然後,預期的輸出將是(1,2,1), (1,2,3) (1,4,1), (1,4,3), (2,1,2) (2,1,4), (2,3,2), (2,3,4) 原因是:在第一行中,有四個有序(1,0)對,其索引爲(2,1), (2,3), (4,1) and (4,3).。同樣,在第二行中,有四個有序(1,0)對,其索引爲(1,2), (1,4), (3,2) and (3,4). 我現在該如何在matlab中逐行編碼。

>> a=[ 0,1,0,1; 1,0,1,0] 

a = 

    0  1  0  1 
    1  0  1  0 

>> b=a(1,:); 
>> b 

b = 

    0  1  0  1 

>> x1=find(b==1) 

x1 = 

    2  4 

>> x0=find(b==0) 

x0 = 

    1  3 

>> [X,Y]=meshgrid(x1,x0); 
>> c=[X(:),Y(:)] 

c = 

    2  1 
    2  3 
    4  1 
    4  3 

>> d=[ repmat(1, [4,1]) c ] 

d = 

    1  2  1 
    1  2  3 
    1  4  1 
    1  4  3 

隨着for循環,這可以解決。我的問題是:你認爲你可以在沒有for循環的情況下在matlab中進行編碼嗎?許多人會爲你的時間和注意力而煩惱。

回答

0

你可以通過巧妙的使用meshgrid來做到這一點。

a = [0,1,0,1;1,0,1,0]; 
[r0, c0] = ind2sub(size(a), find(a == 0)); % row and column of every 0 
[r1, c1] = ind2sub(size(a), find(a == 1)); % row and column of every 1 
[R0, R1] = meshgrid(r0, r1); 
[C0, C1] = meshgrid(c0, c1); 
idx = (R0 == R1); % consider only entries whose rows match 
list = [R0(idx), C1(idx), C0(idx)] 

輸出:

list = 

    1  2  1 
    1  4  1 
    2  1  2 
    2  3  2 
    1  2  3 
    1  4  3 
    2  1  4 
    2  3  4 
相關問題