Azzera filtri
Azzera filtri

How to do loop in the Workspace?

1 visualizzazione (ultimi 30 giorni)
Bruno
Bruno il 20 Set 2016
Modificato: Andrei Bobrov il 20 Set 2016
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

Risposta accettata

Stephen23
Stephen23 il 20 Set 2016
Modificato: Stephen23 il 20 Set 2016
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

Più risposte (2)

Andrei Bobrov
Andrei Bobrov il 20 Set 2016
Modificato: Andrei Bobrov il 20 Set 2016
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 il 20 Set 2016
Modificato: KSSV il 20 Set 2016
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

Categorie

Scopri di più su Data Types in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by