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