MATLAB: How to add up all the elements with condition in a matrix’s column and trouble shooting

sum

Original data is a 270*8 matrix(np), the purpose is to add up all the number above 0 at each column separately. I tried two codes to add up the positive numbers in the second column for example, and they have different outputs. I was wondering why the second code is wrong and is there any way to simplified the first one, so as to create results for all the columns? Thanks!
% correct
clm2=np(:,2)
pos=clm2(clm2>0)
sum1=sum(pos)
% wrong
sum2=sum(np(np(:,2)>0))

Best Answer

YOu must try:
sum2=sum(np(np(:,2)>0,2)) ;
The above line selects, positive elements from column 2. Where as in your code, it will select positive elements from all the columns and add.
Related Question