Add differently sized arrays in one array

Viewed 139

I want to put in a list multiple arrays which could be of different sizes. For instance arrays

  • A with size [300 x 3],
  • B with size [250 x 3], and
  • C with size [450 x 3].

I want to have A, B and C in one list and then if I access the first element of my list it would return to me A with size [300 x 3].

2 Answers

matlab / octave use so-called "cell-arrays" for this purpose. The syntax is similar to arrays, except you use 'braces' ({}) instead of 'brackets' ([]).

e.g.

octave:1> a = [1,2,3], b = [1,2], c = [1,2,3,4]
a =   1   2   3
b =   1   2
c =   1   2   3   4

octave:2> d = {a, b, c}
d =   {
  [1,1] =   1   2   3
  [1,2] =   1   2
  [1,3] =   1   2   3   4
}

Similarly, use braces to 'index' a cell-array and get it's contents:

octave:3> d{1}
ans =   1   2   3

Note: You can also index it like a normal array using parentheses (i.e. ()), but this returns the individual cells themselves (i.e. in cell-array form) rather than their contents:

octave:4> d(1)
ans =   {
  [1,1] =   1   2   3
}

Essentially the 'big' difference between 'normal' (e.g. 'numerical') arrays and 'cell-arrays' is that 'normal' arrays must always contain elements of the same type, whereas in cell-arrays, each element could be anything (including another cell-array).

I would create a struct for your "list". In the follwing example I have done a struct with two elements that have each A,B and C with some data:

% first element of struct
mystruct(1).A = ones(300,3);
mystruct(1).B = ones(250,3);
mystruct(1).C = ones(450,3);

% second element of struct with different data
mystruct(2).A = ones(300,3) + 1;
mystruct(2).B = ones(250,3) + 2;
mystruct(2).C = ones(450,3) + 3;

And it "looks" like:

1x2 mystruct =

  1x2 struct array containing the fields:

    A
    B
    C
Related