How to get columns with means that are greater than one, without using loops?
    8 views (last 30 days)
  
       Show older comments
    
Hi, Its kind of a silly question, but for some reason nothing popped into my mind - I wanna get columns of some matrix where for each column, his mean is greater than one, without using loops. i.e,perform what this code does without the loop:
bigMeters=zeros(1,size(bestMatDiff,2)); %some matrix 
for i_col=1:size(bestMatDiff,2)
    col=bestMatDiff(:,i_col);
    bigMeters(i_col)=(mean(col(col~=0))>1);
end
Thanks, Gal
EDIT: sorry, I forgot to mention that its the mean of the non-zero entries that I want, as can be seen in the code (otherwise its really a dumb question :)
0 Comments
Accepted Answer
  Andrei Bobrov
      
      
 on 18 Sep 2013
        
      Edited: Andrei Bobrov
      
      
 on 18 Sep 2013
  
      p1 = bestMatDiff;
p1(p1 == 0) = nan;
p2 = nanmean(p1);
out = p1(:,p2 > 1);
or
p1 = bestMatDiff;
t = p1 ~= 0;
p2 = sum(p1)./sum(t);
out = p1(:,p2 > 1);
0 Comments
More Answers (1)
  Geert
      
 on 18 Sep 2013
        
      Edited: Geert
      
 on 18 Sep 2013
  
      Hi Gal,
you can find an example in the following code:
% generate random matrix
randomMatrix = 1+randn(10,10);
% specify your threshold (in your case this is 1)
threshold = 1;
% calculate the mean of each column
columnMean = mean(randomMatrix,1);
% if you want to get the "bigMeters" variable from your code, you can add
% the following line of code:
bigMeters = columnMean > threshold;
% the matrix with columns of mean greater than the threshold
newMatrix = randomMatrix(:,columnMean>threshold);
% if you want to now at which column index these columns are, you can find
% them with the "find" command
columnIndices = find(columnMean>threshold);
% % newMatrix can than also be found with the following command:
% newMatrix = randomMatrix(:,columnIndices);
The trick is to use logical indexing, which is done in the line newMatrix = randomMatrix(:,columnMean>threshold);
The find command provides an alternative method.
0 Comments
See Also
Categories
				Find more on Creating and Concatenating Matrices in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

