9

I have a 2D cell array. I want to do the following:

y = some_number;
row(x) = [row(x)  another_row(y)];

However, row(x) isn't defined until this happens so it doesn't work! How do I simply append another_row(y) onto row(x) when row(x) may not be defined?

Sorry this is easy to do in other languages but I'm not sure how in MATLAB!

Thank you.

Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
ale
  • 11,636
  • 27
  • 92
  • 149
  • It's not perfectly clear what you're trying to do. Could you give a concrete example of what might be in your array beforehand and what you want to be in it afterwards? Or some code in another language in which it's easy? – Gareth McCaughan Mar 09 '11 at 18:21

1 Answers1

15

You can first initialize row to be an empty array (or cell array) as follows:

row = [];  %# Empty array
row = {};  %# Empty cell array

Then you can append a new row to the array (or a new cell to the cell array) like so:

row = [row; another_row(y)];    %# Append a row to the array
row = [row; {another_row(y)}];  %# Append a cell to the cell array

See the documentation for more information on creating and concatenating matrices.

It should also be noted that growing arrays like this is not very efficient. Preallocating an array, assuming you know the final size it will be, is a much better idea. If you don't know the final size, allocating array elements in chunks will likely be more efficient than allocating them one row at a time.

Community
  • 1
  • 1
gnovice
  • 125,304
  • 15
  • 256
  • 359