Clear Filters
Clear Filters

How to write for-loop?

1 view (last 30 days)
Sergey Dukman
Sergey Dukman on 21 Sep 2015
Commented: Stephen23 on 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

Accepted Answer

Kirby Fears
Kirby Fears on 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.

More Answers (0)

Categories

Find more on Operators and Elementary Operations 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!