![]() |
如何在MATLAB中将函数应用于矩阵的每一行/每一列?
您可以通过说例如v + 1将函数arrayfun向量中的每个项目,也可以使用函数arrayfun 。如何在不使用for循环的情况下为矩阵的每一行/每一列执行此操作?
[B]回答:[/B] 许多内置操作(例如[URL="http://www.mathworks.com/help/matlab/ref/sum.html"]sum[/URL]和[URL="http://www.mathworks.com/help/matlab/ref/prod.html"]prod[/URL]已经可以跨行或跨列进行操作,因此您可以重构要利用的功能。 如果这不是可行的选择,那么一种方法是使用[URL="http://www.mathworks.com/help/matlab/ref/mat2cell.html"]mat2cell[/URL]或[URL="http://www.mathworks.com/help/matlab/ref/num2cell.html"]num2cell[/URL]将行或列收集到单元格中,然后使用[URL="http://www.mathworks.com/help/matlab/ref/cellfun.html"]cellfun[/URL]对所得的单元格数组进行操作。 例如,假设您要对矩阵M的列求和。您可以简单地使用[URL="http://www.mathworks.com/help/matlab/ref/sum.html"]sum[/URL]来做到这一点: M = magic(10); %# A 10-by-10 matrix columnSums = sum(M, 1); %# A 1-by-10 vector of sums for each column 这是使用更复杂的[URL="http://www.mathworks.com/help/matlab/ref/num2cell.html"]num2cell[/URL] / [URL="http://www.mathworks.com/help/matlab/ref/cellfun.html"]cellfun[/URL]选项的方法: 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 [url=https://stackoverflow.com/questions/2307249]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 06:59。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.