How to do loop in the Workspace?
1 回表示 (過去 30 日間)
古いコメントを表示
I have four matrixes c1 c2 c3 c4 (each matrix is 45x9)in the workspace. I need to calculate the mean for each row in each matrix.
The code I tried does not work:
c = {c1, c2, c3, c4};
for j = 1:4
mean_c(j) = mean(c{j},2);
end
0 件のコメント
採用された回答
Stephen23
2016 年 9 月 20 日
編集済み: Stephen23
2016 年 9 月 20 日
Method One: for loop:
c = {rand(45,9), rand(45,9), rand(45,9), rand(45,9)};
d = cell(size(c));
for k = 1:numel(c)
d{k} = mean(c{k},2);
end
Method Two: cellfun:
d = cellfun(@(m)mean(m,2),c,'UniformOutput',false);
Convert to numeric by simply using cell2mat:
>> cell2mat(d)
ans =
0.49524 0.40269 0.65561 0.47278
0.59244 0.52532 0.41187 0.42431
0.34457 0.58936 0.54098 0.55274
0.52958 0.62364 0.50265 0.52148
0.70699 0.65555 0.58959 0.48702
0.38250 0.34663 0.54874 0.48712
0.59373 0.44404 0.62564 0.39276
0.48016 0.59843 0.57385 0.48644
0.49235 0.52315 0.52946 0.53855
0.51168 0.69419 0.46208 0.35696
0.53927 0.46378 0.48168 0.49156
etc
0 件のコメント
その他の回答 (2 件)
Andrei Bobrov
2016 年 9 月 20 日
編集済み: Andrei Bobrov
2016 年 9 月 20 日
C = cat(1,c1,c2,c3,c4);
d = reshape(mean(C,2),size(c1,1),[]);
or
C = cat(1,c{:});
d = reshape(mean(C,2),size(c1,1),[]);
0 件のコメント
KSSV
2016 年 9 月 20 日
編集済み: KSSV
2016 年 9 月 20 日
clc;close all;clear all;
% Take some random data for c1,c2,c3,c4
c1 = rand(45,9) ;
c2 = rand(45,9) ;
c3 = rand(45,9) ;
c4 = rand(45,9) ;
c{1} = c1 ;
c{2} = c2 ;
c{3} = c3 ;
c{4} = c4 ;
mean_c = zeros(45,4) ; % initialize the mean for each ci
for j = 1:4
mean_c(:,j) = mean(c{j},2);
end
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!