Search code examples
matlabmatrixcell-array

Cell array or matrix for different element's sizes per iteration


No code just visually:

Iteration i              result j1                  result j2
     1                   10 15 20 15 25                2 
     2                   5                             8
     .                   . . .                         .
     .                   . . . . . .                   .
     i           j1 with length(x), x=0:100        j2 with length == 1

edit for better representation:

                [10 15 20 15 25]          [1]                (i=1)
                [5]                       [2]                (i=2)
Matrix(i) = [   [. . . . . . . ]          [3]          ]
                [..]                      [.]
                [j1 = size (x)]     [j2 size 1 * 1]          (i=100)

so Matrix dimension is: i (rows) * 2 (columns) 

(p.e for i = 1, j1 with size(x) column 1 on row 1, j1 size (1) column 2 on row 1)

I want to save each iterations results to a matrix in order to use them for comparison. Can this be done with a matrix or its better with cell array and please write an example for reference.

Thanks in advance.


Solution

  • I would go with a cell array for a cleaner, more intuitive implementation, with less contraints.

    nIterations = 500;
    J = cell(nIterations, 2);
    for i=1:nIterations
        length_x = randi(100); % random size of J1
        J{i,1} = randi(100, length_x, 1); % J1
        J{i,2} = randi(i); % J2
    end
    

    In addition you get some extra benefits such as:

    • Access an element along and within the cell array

      J{10, 1}; J{10, 2};

    • Append/modify within each element without changing the overall structure

      J{10, 1} = [J{10, 1}; 0]

    • Append to the array (adding iterations), like in a normal array

      J{end+1, 1} = 1; J{end, 2} = 1

    • Apply functions in each entry (vector) using cellfun

      length_J = cellfun(@length, J); % get numel/length of J1
      mean_J = cellfun(@mean, J); % get mean of J1