如何将函数应用于 MATLAB 中矩阵的每一行/列? [英] How can I apply a function to every row/column of a matrix in MATLAB?
问题描述
您可以将函数应用于向量中的每一项,例如,v + 1
,或者您可以使用函数 arrayfun
.如何在不使用 for 循环的情况下为矩阵的每一行/列执行此操作?
You can apply a function to every item in a vector by saying, for example, v + 1
, or you can use the function arrayfun
. How can I do it for every row/column of a matrix without using a for loop?
推荐答案
许多内置操作,例如 sum
和 prod
已经能够跨行或跨列操作,因此您可以重构您正在应用的函数以利用这一点.
Many built-in operations like sum
and prod
are already able to operate across rows or columns, so you may be able to refactor the function you are applying to take advantage of this.
如果这不是一个可行的选择,一种方法是使用 mat2cell
或 num2cell
,然后使用 cellfun
对生成的元胞数组进行操作.
If that's not a viable option, one way to do it is to collect the rows or columns into cells using mat2cell
or num2cell
, then use cellfun
to operate on the resulting cell array.
例如,假设您要对矩阵 M
的列求和.您只需使用 sum
即可完成此操作:
As an example, let's say you want to sum the columns of a matrix M
. You can do this simply using sum
:
M = magic(10); %# A 10-by-10 matrix
columnSums = sum(M, 1); %# A 1-by-10 vector of sums for each column
这里是如何使用更复杂的num2cell
/cellfun
选项:
And here is how you would do this using the more complicated num2cell
/cellfun
option:
M = magic(10); %# A 10-by-10 matrix
C = num2cell(M, 1); %# Collect the columns into cells
columnSums = cellfun(@sum, C); %# A 1-by-10 vector of sums for each cell
这篇关于如何将函数应用于 MATLAB 中矩阵的每一行/列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!