如何在MATLAB中按列总和划分矩阵元素? [英] How do I divide matrix elements by column sums in MATLAB?

查看:99
本文介绍了如何在MATLAB中按列总和划分矩阵元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法将每个矩阵元素除以列总和?例如:

Is there an easy way to divide each matrix element by the column sum? For example:

input:

1  4

4  10

output:

1/5  4/14

4/5  10/14

推荐答案

以下是执行此操作的不同方法的列表...

Here's a list of the different ways to do this ...

B = bsxfun(@rdivide,A,sum(A));

  • ...使用 repmat :

  • ... using repmat:

    B = A./repmat(sum(A),size(A,1),1);
    

  • ...使用外部产品(由 Amro ):

  • ... using an outer product (as suggested by Amro):

    B = A./(ones(size(A,1),1)*sum(A));
    

  • ...并使用for循环(如 mtrw 所建议):

  • ... and using a for loop (as suggested by mtrw):

    B = A;
    columnSums = sum(B);
    for i = 1:numel(columnSums)
      B(:,i) = B(:,i)./columnSums(i);
    end
    

  • 更新:

    从MATLAB R2016b及更高版本开始,大多数内置的二进制函数(可以在 bsxfun 默认情况下.因此,在最新的MATLAB版本中,您要做的就是:

    As of MATLAB R2016b and later, most built-in binary functions (list can be found here) support implicit expansion, meaning they have the behavior of bsxfun by default. So, in the newest MATLAB versions, all you have to do is:

    B = A./sum(A);
    

    这篇关于如何在MATLAB中按列总和划分矩阵元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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