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