MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   如何在MATLAB中按列总和划分矩阵元素? (https://www.labfans.com/bbs/showthread.php?t=22925)

poster 2019-12-10 16:49

如何在MATLAB中按列总和划分矩阵元素?
 
是否有一种简单的方法将每个矩阵元素除以列总和?例如:

input: 1 4 4 10 output: 1/5 4/14 4/5 10/14
回答:
以下是执行此操作的不同方法的列表...
[LIST][*] ...使用[URL="https://www.mathworks.com/help/matlab/ref/bsxfun.html"]bsxfun[/URL] :

B = bsxfun(@rdivide,A,sum(A));[*] ...使用[URL="https://www.mathworks.com/help/matlab/ref/repmat.html"]repmat[/URL] :

B = A./repmat(sum(A),size(A,1),1);[*] ...使用[URL="http://en.wikipedia.org/wiki/Outer_product"]外部产品[/URL] (如[URL="https://stackoverflow.com/users/97160/amro"]Amro[/URL]建议):

B = A./(ones(size(A,1),1)*sum(A));[*] ...并使用for循环(如[URL="https://stackoverflow.com/users/120261/mtrw"]mtrw[/URL]所建议):

B = A; columnSums = sum(B); for i = 1:numel(columnSums) B(:,i) = B(:,i)./columnSums(i); end[/LIST][B]更新:[/B]

从MATLAB R2016b及更高版本开始,大多数内置二进制函数(可在[URL="https://www.mathworks.com/help/matlab/ref/bsxfun.html#inputarg_fun"]此处[/URL]找到列表)支持隐式扩展,这意味着它们默认情况下具有[URL="https://www.mathworks.com/help/matlab/ref/bsxfun.html"]bsxfun[/URL]的行为。因此,在最新的MATLAB版本中,您要做的就是:

B = A./sum(A);

[url=https://stackoverflow.com/questions/1773099]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 00:55

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.