![](/img/trans.png)
[英]Is there a way to make chunks of mean values of the 2nd dimension of a 3D array while maintaining other dimensions?
[英]sortrows in the 2nd dimension of 3d matrix
我试图在Matlab的3d矩阵的第二维中排序第一行,但sortrows()在这种情况下不起作用。
例如,我有一个像矩阵
a(:,:,1)
1 2 4
3 1 6
2 0 5
a(:,:,2)
3 5 6
1 2 4
0 2 2
我需要得到结果
a(:,:,1)
1 2 4
2 0 5
3 1 6
a(:,:,2)
0 2 2
1 2 4
3 5 6
有没有一种有效的方法来实现这一目标? 非常感谢!
如果我理解正确,您希望根据第一 列的值对每个第三个暗淡切片中的 行进行排序 。
[m,n,p] = size(a);
[~, row_ind] = sort(a(:,1,:), 1);
lin_ind = bsxfun(@plus, bsxfun(@plus, row_ind, (0:n-1)*m), reshape((0:p-1)*m*n, 1, 1, p));
result = a(lin_ind);
这是如何工作的 :
排序a(:,1:,)
沿着所述第一维度(行),并得到分选的索引(使用的第二输出sort
;第2行)。 从那些行索引中,生成将给出所需结果的线性索引 (使用bsxfun
;第3行)(第4行)。
示例 :
用于输入
a(:,:,1) = [1 2 4
3 1 6
2 0 5];
a(:,:,2) = [3 5 6
1 2 4
0 2 2];
这会产生
result(:,:,1) =
1 2 4
2 0 5
3 1 6
result(:,:,2) =
0 2 2
1 2 4
3 5 6
只需对每个2d矩阵使用sortrows
:
a(:,:,1)=sortrows(a(:,:,1));
a(:,:,2)=sortrows(a(:,:,2));
当然你可以循环完成
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.