Reputation: 41
I see this question: How do I divide matrix elements by column sums in MATLAB?
But additionally, I want to do the division only if the column sum (sum(A)
) is non-zero.
Will any of the listed methods there work, except for the loop-method as it is very slow for my matrix size?
Upvotes: 0
Views: 148
Reputation: 114866
All you need is do remove the zero elements from sum(A)
with an intermediate step:
col_sum = sum(A);
col_sum( col_sum == 0 ) = 1; % no zeros
Now you can use any method in the linked post, e.g. using bsxfun
:
B = bsxfun(@rdivide, A, col_sum);
From numerical point of view, eliminating only elements that are exactly zero when A
is a floating point type, is not a very good practice. Instead you might want to eliminate all close to zero elements:
col_sum( abs(col_sum) < 1e-10 ) = 1;
Upvotes: 1