![](/img/trans.png)
[英]How can I efficently use Matlab to find the all the variances along the third dimension of a 3D array?
[英]use find along third dimension
我有一个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
使用重塑时出错要重塑形状,元素的数量不得更改。
我看不到解决方法。
我还尝试将find
与“ first”选项一起使用,但没有成功。
您可以使用max
函数的第二个输出:
[~,idx]=max(a>2,[],3);
找到值大于2的逻辑索引,然后将其转换为两倍,以便可以用NaN
代替0。 添加常量以表示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
在做一些数学运算时,我想到了以下这种方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.