Dennis Alders
Dennis Alders

Reputation: 41

Saving all values generated by a for loop

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?

Upvotes: 0

Views: 82

Answers (2)

lakshmen
lakshmen

Reputation: 29064

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..

Upvotes: 0

Shai
Shai

Reputation: 114786

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 );
    

Upvotes: 1

Related Questions