Azzera filtri
Azzera filtri

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

3 visualizzazioni (ultimi 30 giorni)
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 :)

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 18 Set 2013
Modificato: Andrei Bobrov il 18 Set 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);

Più risposte (1)

Geert
Geert il 18 Set 2013
Modificato: Geert il 18 Set 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.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by