How to get columns with means that are greater than one, without using loops?

조회 수: 3 (최근 30일)
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 :)

채택된 답변

Andrei Bobrov
Andrei Bobrov 2013년 9월 18일
편집: Andrei Bobrov 2013년 9월 18일
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);

추가 답변 (1개)

Geert
Geert 2013년 9월 18일
편집: Geert 2013년 9월 18일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by