필터 지우기
필터 지우기

How to write for-loop?

조회 수: 1 (최근 30일)
Sergey Dukman
Sergey Dukman 2015년 9월 21일
댓글: Stephen23 2015년 9월 22일
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

채택된 답변

Kirby Fears
Kirby Fears 2015년 9월 21일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by