matlab - 如何沿着数组的某个维度进行操作?

标签 matlab optimization multidimensional-array vectorization slice

我有一个包含五个 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 的文档中注意到的一个常见模式, meanstd是它们允许指定额外的 dim 输入。例如,在 max 中:

M = max(A,[],dim) returns the largest elements along dimension dim. For example, if A is a matrix, then max(A,[],2) is a column vector containing the maximum value of each row.

如何使用此语法来简化我的代码?

最佳答案

当计算结果很重要时,MATLAB 中的许多函数都允许指定“要操作的维度”(几个常见示例是:minmax , sum, prod, mean, std, size, 中位数, prctile, bounds) - 这对于多维输入尤为重要。当未指定 dim 输入时,MATLAB 有一种自行选择维度的方法,如文档中所述;例如在 max 中:

  • If A is a vector, then max(A) returns the maximum of A.
  • If A is a matrix, then max(A) is a row vector containing the maximum value of each column.
  • If A is a multidimensional array, then max(A) operates along the first array dimension whose size does not equal 1, treating the elements as vectors. The size of this dimension becomes 1 while the sizes of all other dimensions remain the same. If A is an empty array whose first dimension has zero length, then max(A) returns an empty array with the same size as A.

然后,使用...,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/

相关文章:

java - 如何操作嵌套的 for 循环

php - 子数组中所有元素的总和 - PHP

c - Mex 文件点积

java - 在 Java 中初始化二维数组

MATLAB 设置颜色图颜色范围

java - 向下转换对象的时间复杂度是多少?

mysql - 如何在 where 子句中优化 mysql 中的日期时间比较

c++ - 通过 istringstream 的 c++ 字符串标记化的性能开销

c++ - qtCreator 错误 : can't map file, errno=22 架构 x86_64 文件?

matlab - 如何使用 matlab 对具有负值的向量进行归一化?