我有一个包含五个 3×4 切片的 3D 数组,定义如下:
rng(3372061);
M = randi(100,3,4,5);
我想收集一些关于数组的统计信息:
- 每列中的最大值。
- 每一行的平均值。
- 每个切片内的标准偏差。
这使用循环非常简单,
sz = size(M);
colMax = zeros(1,4,5);
rowMean = zeros(3,1,5);
sliceSTD = zeros(1,1,5);
for indS = 1:sz(3)
sl = M(:,:,indS);
sliceSTD(indS) = std(sl(1:sz(1)*sz(2)));
for indC = 1:sz(1)
rowMean(indC,1,indS) = mean(sl(indC,:));
end
for indR = 1:sz(2)
colMax(1,indR,indS) = max(sl(:,indR));
end
end
但我不确定这是解决问题的最佳方法。
我在 max
的文档中注意到的一个常见模式, mean
和 std
是它们允许指定额外的 dim
输入。例如,在 max
中:
M = max(A,[],dim)
returns the largest elements along dimensiondim
. For example, ifA
is a matrix, thenmax(A,[],2)
is a column vector containing the maximum value of each row.
如何使用此语法来简化我的代码?
最佳答案
当计算结果很重要时,MATLAB 中的许多函数都允许指定“要操作的维度”(几个常见示例是:min
、max
, sum
, prod
, mean
, std
, size
, 中位数
, prctile
, bounds
) - 这对于多维输入尤为重要。当未指定 dim
输入时,MATLAB 有一种自行选择维度的方法,如文档中所述;例如在 max
中:
- If
A
is a vector, thenmax(A)
returns the maximum ofA
.- If
A
is a matrix, thenmax(A)
is a row vector containing the maximum value of each column.- If
A
is a multidimensional array, thenmax(A)
operates along the first array dimension whose size does not equal1
, treating the elements as vectors. The size of this dimension becomes1
while the sizes of all other dimensions remain the same. IfA
is an empty array whose first dimension has zero length, thenmax(A)
returns an empty array with the same size asA
.
然后,使用...,dim)
语法我们可以重写代码如下:
rng(3372061);
M = randi(100,3,4,5);
colMax = max(M,[],1);
rowMean = mean(M,2);
sliceSTD = std(reshape(M,1,[],5),0,2); % we use `reshape` to turn each slice into a vector
这有几个优点:
- 代码更容易理解。
- 代码可能更健壮,能够处理超出最初设计范围的输入。
- 代码可能更快。
总而言之:阅读您正在使用的函数的文档并尝试不同的语法总是一个好主意,以免错过使您的代码更简洁的类似机会。
关于matlab - 如何沿着数组的某个维度进行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49510413/