フィルターのクリア

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 Center および File ExchangeOperators and Elementary Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by