问题描述
我有一个3D数组,其中包含五个3×4切片,定义如下:
I have a 3D array containing five 3-by-4 slices, defined as follows:
rng(3372061);
M = randi(100,3,4,5);
我想收集有关数组的一些统计信息:
I'd like to collect some statistics about the array:
- 每列中的最大值.
- 每一行的平均值.
- 每个切片中的标准差.
使用循环非常简单
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
但是我不确定这是否是解决问题的最佳方法.
But I'm not sure that this is the best way to approach the problem.
我在 max
的文档中注意到的一种常见模式>, mean
和 std
是因为它们允许指定其他dim
输入.例如,在max
中:
A common pattern I noticed in the documentation of max
, mean
and std
is that they allow to specify an additional dim
input. For instance, in max
:
如何使用此语法简化代码?
How can I use this syntax to simplify my code?
推荐答案
当计算结果很重要时,MATLAB中的许多函数都允许规范维运算"(几个常见示例:min
,max
,sum
,prod
,mean
,std
,size
,median
,prctile
,bounds
)-对于多维输入尤其重要.如未说明,未指定dim
输入时,MATLAB可以自行选择尺寸.例如在max
:
Many functions in MATLAB allow the specification of a "dimension to operate over" when it matters for the result of the computation (several common examples are: min
, max
, sum
, prod
, mean
, std
, size
, median
, prctile
, bounds
) - which is especially important for multidimensional inputs. When the dim
input is not specified, MATLAB has a way of choosing the dimension on its own, as explained in the documentation; for example in max
:
然后,使用...,dim)
语法,我们可以按如下所示重写代码:
Then, using the ...,dim)
syntax we can rewrite the code as follows:
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
这有几个优点:
- 代码更易于理解.
- 该代码可能更健壮,能够处理超出最初设计目的的输入.
- 代码可能更快.
总而言之:最好阅读正在使用的函数的文档,并尝试不同的语法,以免错过相似的机会来使您的代码更简洁.
In conclusion: it is always a good idea to read the documentation of functions you're using, and experiment with different syntaxes, so as not to miss similar opportunities to make your code more succinct.
这篇关于如何沿着数组的特定维度执行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!