2017-09-23 63 views
2

我有一個2 * 3 * 3的矩陣a使用發現沿第三維

a=[1 1 1;1 1 1]; 
a(:,:,2)=[1 1 1;1 1 1]+1; 
a(:,:,3)=[1 1 1;1 1 1]+2; 

認爲第三個維度的深度值。我想找到在該a大於2。在這種情況下,結果應該是深度:

[3 3 3;3 3 3] 

有沒有辦法做到在一個量化的方式?

我嘗試

我嘗試以下,但它不是做得比較工作:

inds=find(a>2) %find indices of elements>2 
lev=ceil(inds/2/3) %divide by the size of each layer. it returns the layer indices on which the an element>2 is 

depths = reshape(lev,2,3) 

inds = 

    13 
    14 
    15 
    16 
    17 
    18 


lev = 

    3 
    3 
    3 
    3 
    3 
    3 

depths = 

    3  3  3 
    3  3  3 

在這種情況下工作,但它是一個幸運的情況。

如果我使用:

a=[1 1 1;1 1 2]; 
a(:,:,2)=[1 1 1;1 1 2]+1; 
a(:,:,3)=[1 1 1;1 1 2]+2; 

現在不能因爲一起的最後一列工作,我有一個以上的值大於2.事實上:使用

inds=find(a>2) %find indices of elements>2 
lev=ceil(inds/2/3) %divide by the size of each layer. it returns the layer indices on which the an element>2 is 

depths = reshape(lev,2,3) 

inds = 

    12 
    13 
    14 
    15 
    16 
    17 
    18 


lev = 

    2 
    3 
    3 
    3 
    3 
    3 
    3 

inds = 

    12 
    13 
    14 
    15 
    16 
    17 
    18 


lev = 

    2 
    3 
    3 
    3 
    3 
    3 
    3 

錯誤重塑 要RESHAPE元素的數量不能改變。

我看不到解決方法。

我也試着用'第一'選項使用find,但根本沒有成功。

+0

但是你希望深度中的所有元素大於2或至少有一個元素大於2? –

+0

每個第三維列的第一個元素。如果我們使用(x,y,z)座標,我需要每個(x,y)對的第一個z – shamalaia

+0

第二種情況下應該輸出什麼? – codeaviator

回答

4

你可以使用max函數的第二個輸出離子:

[~,idx]=max(a>2,[],3); 
1

查找值大於2的邏輯索引,然後將其轉換爲雙精度值,以便0可以替換爲NaN s。添加一個常量來表示3D切片的數量。然後最後使用min找到沿第三維的最小值,忽略NaN s。

depth = double(a>2); %Finding logical indices where values > 2 and converting to double 
depth(depth==0)=NaN; %Replacing zeros with NaNs 
depth=bsxfun(@plus,depth,reshape(0:2,1,1,[])); %Adding const representing # of 3D slice 
%If you have R2016b or later, you can use implicit expansion i.e 
%    depth=depth+reshape(0:2,1,1,[]); instead of the last step 
depth=min(depth,[],3);%Finding the minimum value along the third dimension 
+0

謝謝!但是我不得不使用'depth = depth + repmat(reshape(0:2,1,1,[]),2,3);否則我得到一個錯誤('數組維數必須與二進制數組匹配。') 。你同意嗎? – shamalaia

+0

@shamalaia我之前使用過隱式擴展(在R2016b中引入)。現在我添加了適用於早期版本的'bsxfun'版本。 –

1

做一些數學我想出了這樣一行代碼:

1 + size(a, 3)*ones(size(a, 1), size(a, 2)) - sum(a > 2, 3) 

測試案例1:

>> a=[1 1 1;1 1 1]; 
a(:,:,2)=[1 1 1;1 1 1]+1; 
a(:,:,3)=[1 1 1;1 1 1]+2; 

>> 1 + size(a, 3)*ones(size(a, 1), size(a, 2)) - sum(a > 2, 3) 

ans = 

    3  3  3 
    3  3  3 

測試案例2:

>> a=[1 1 1;1 1 2]; 
a(:,:,2)=[1 1 1;1 1 2]+1; 
a(:,:,3)=[1 1 1;1 1 2]+2; 

>> 1 + size(a, 3)*ones(size(a, 1), size(a, 2)) - sum(a > 2, 3) 

ans = 

    3  3  3 
    3  3  2