开发者

Simple 2D cell array appending

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_r开发者_运维问答ow(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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜