필터 지우기
필터 지우기

How to do loop in the Workspace?

조회 수: 1 (최근 30일)
Bruno
Bruno 2016년 9월 20일
편집: Andrei Bobrov 2016년 9월 20일
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

채택된 답변

Stephen23
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

추가 답변 (2개)

Andrei Bobrov
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),[]);

KSSV
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

카테고리

Help CenterFile Exchange에서 Data Types에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by