7

In Matlab, I want to create a two-dimensional array. However, I cannot create a matrix, because the rows are all different lengths.

I am new to Matlab, and I would normally do this in C++ by creating an array of pointers, with each pointer pointing towards its own array.

How should I do this in Matlab? Thanks.

Dan
  • 45,079
  • 17
  • 88
  • 157
Karnivaurus
  • 22,823
  • 57
  • 147
  • 247

3 Answers3

11

You can use cell arrays, which can contain data of varying types and sizes.

Like this:

data = {[1]; [2,2]; [3,3,3]};

Check out here for more examples.

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
5

You could use a cell array:

C = {[1,2,3];
     [1,2,3,4,5];
     [1,2]};

Or pad with NaN or 0 or Inf etc

N = [1, 2, 3,   NaN, NaN;
     1, 2, 3,   4,   5;
     1, 2, NaN, NaN, NaN]

It really depends on what you will be doing with your data next

Dan
  • 45,079
  • 17
  • 88
  • 157
4

Use cell ararys as mentioned by others. Listing out some code and comments to explain it -

%%// Create a cell array to store data
Arr = {[1 3 4 6 8]; 
       [1 8 3]; 
       [4 6 3 2];
       [6 3 6 2 6 8]}

%%// Access element (3,4)
element = Arr{3}(4)

Outputs

Arr = 

    [1x5 double]
    [1x3 double]
    [1x4 double]
    [1x6 double]


element =

     2
Divakar
  • 218,885
  • 19
  • 262
  • 358