Effacer les filtres
Effacer les filtres

How to write for-loop?

1 vue (au cours des 30 derniers jours)
Sergey Dukman
Sergey Dukman le 21 Sep 2015
Commenté : Stephen23 le 22 Sep 2015
Hello, Is it possible to create a for-loop which evaluates mean values of 12 (in my case) vectors, which has different dimensions? For example a=[1 2 3 5 4] and b=[1 1 2 5 6 8 9], find mean values using for-loop.
Thank you in advance. Sergey

Réponse acceptée

Kirby Fears
Kirby Fears le 21 Sep 2015
Hi Sergey,
This sample code will do what you're looking for:
% sample of vectors
a=rand(10,1);
b=rand(9,1);
c=rand(8,1);
% vector names
vecs={'a','b','c'};
% pre-allocating vector of means
meanvec=NaN(numel(vecs),1);
% taking means
for iter=1:numel(vecs),
meanvec(iter)=mean(eval(vecs{iter}));
end
However, this requires you to type out each variable name in "vecs". This operation would be much easier if you had stored all of your vectors into a cell to begin with, as I'm doing in the example below:
% sample of vectors
vecset=cell(3,1);
vecset{1}=rand(10,1);
vecset{2}=rand(9,1);
vecset{3}=rand(8,1);
% calculating mean of each vector
meanvec=cellfun(@(c)mean(c),vecset);
Hope this helps.

Plus de réponses (0)

Catégories

En savoir plus sur Operators and Elementary Operations dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by