Borrar filtros
Borrar filtros

How to do loop in the Workspace?

1 visualización (últimos 30 días)
Bruno
Bruno el 20 de Sept. de 2016
Editada: Andrei Bobrov el 20 de Sept. de 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

Respuesta aceptada

Stephen23
Stephen23 el 20 de Sept. de 2016
Editada: Stephen23 el 20 de Sept. de 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

Más respuestas (2)

Andrei Bobrov
Andrei Bobrov el 20 de Sept. de 2016
Editada: Andrei Bobrov el 20 de Sept. de 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 el 20 de Sept. de 2016
Editada: KSSV el 20 de Sept. de 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

Categorías

Más información sobre Data Types en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by