MATLAB: How to write for-loop

mean values of vectors

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

Best Answer

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.