gpt4 book ai didi

arrays - 在 3d 矩阵的第二维中排序

转载 作者:太空宇宙 更新时间:2023-11-03 19:55:19 25 4
gpt4 key购买 nike

我试图在 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

有没有一种有效的方法来实现这一目标?非常感谢!

最佳答案

如果我理解正确,你想排序 each third-dim slice 根据第一个的值。

[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 行)。从这些行索引中生成 linear indices (使用 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

关于arrays - 在 3d 矩阵的第二维中排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30412770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com