Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple 2D cell array appending

Tags:

matlab

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.

like image 329
ale Avatar asked Mar 09 '11 18:03

ale


1 Answers

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.

like image 96
gnovice Avatar answered Oct 09 '22 09:10

gnovice