我如何将函数应用于MATLAB中矩阵的每一行/列? [英] How can I apply a function to every row/column of a matrix in MATLAB?

查看:148
本文介绍了我如何将函数应用于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆