How do I divide matrix elements by column sums in MATLAB?

后端 未结 3 2257
借酒劲吻你
借酒劲吻你 2020-12-01 06:54

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
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 07:22

    Couldn't resist trying a list comprehension. If this matrix was represented in a row-major list of lists, try this:

    >>> A = [[1,4],[4,10]]
    >>> [[float(i)/j for i,j in zip(a,map(sum,zip(*A)))] for a in A]
    [[0.20000000000000001, 0.2857142857142857], [0.80000000000000004, 0.7142857142857143]]
    

    Yes, I know that this is not super-efficient, as we compute the column sums once per row. Saving this in a variable named colsums looks like:

    >>> colsums = map(sum,zip(*A))
    >>> [[float(i)/j for i,j in zip(a,colsums)] for a in A]
    [[0.20000000000000001, 0.2857142857142857], [0.80000000000000004, 0.7142857142857143]]
    

    Note that zip(*A) gives transpose(A).

提交回复
热议问题