0

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?

Community
  • 1
  • 1

1 Answers1

1

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; 
Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371