0

So, I am new to MatLab and I am trying something of which I am sure it is possible. I'm not sure how though.

Here's what I'm trying in a nutshell: I generate a string of outcomes (M) from matrix C. Matrix C consists of 16 cells (4x4 cells, each cell is 90x6). From each of these cells I try to compute the mean value. This gives me the mean values, but rewrites M after each iteration:

for i=1:4;
for j=1:4;
M=mean2(C{i,j})
end
end

What I need is a matrix of 4x4 wherein the mean values for all of C's cells are listed, how do I do that?

Dennis Alders
  • 41
  • 1
  • 1
  • 2

2 Answers2

1
M = zeros( 4 ); %// pre-allocate !!!
for ii=1:4;
    for jj=1:4;
        M(ii,jj)=mean2(C{ii,jj})
    end
end

A few pointers:

  1. Pre-allocation - it is a very good practice to pre-allocate arrays that are being updated in loops.
    See, for example, this thread.

  2. It is best not to use i and j as variable names in Matlab.

  3. You might find cellfun a useful tool when working with cell arrays:

    M = cellfun( @mean2, C );
    
Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
  • well done for the `ii` and `jj`, although I never use them myself, I always forget to remind people that they are not recommended. – Hoki Sep 21 '14 at 12:51
0

Two ways:

1) To preallocate as @Shai said:

M = zeros( 4 );
for ii=1:4;
    for jj=1:4;
        M(ii,jj)=mean2(C{ii,jj})
    end
end

2) To append to the previous element in the array

M = [];
for i=1:4;
for j=1:4;
M=[M;mean2(C{i,j})];
end
end

Method 1 is definitely way better. But wanted to inform you there are two methods..

lakshmen
  • 28,346
  • 66
  • 178
  • 276