Add first element to a cell array

99 次查看(过去 30 天)
Dear,
I would like to add a new element in the first position in an cell array For example if ArrCell={[1],[2],[3],[4],[5]} is the existing cell and [new] is a matrix. I would like to get ArrCell={[new],[1],[2],[3],[4],[5]}
Of course, I can get this result using a temporal cell array and looping over all the elements of the existing one, but the quesion is if there an efficient way to get this result
Thanks in advance,

采纳的回答

Adam
Adam 2015-12-18
ArrCell = [ { new }, ArrCell ];
should work. I'm not at my machine with Matlab at the moment so can't double-check, but fairly sure that works.
  5 个评论
Adam
Adam 2020-3-20
ArrCell was a row array. You can't concatenate vertically a scalar and a 5-element row array.
Image Analyst
Image Analyst 2020-3-20
new = magic(3) % A matrix
ArrCell={[1],[2],[3],[4],[5]} % A cell array
ArrCell = [ { new }, ArrCell ] % Adam uses comma
ArrCell2 = [ { new }; ArrCell ]; % Daniel uses semicolon
new =
8 1 6
3 5 7
4 9 2
ArrCell =
1×5 cell array
{[1]} {[2]} {[3]} {[4]} {[5]}
ArrCell =
1×6 cell array
{3×3 double} {[1]} {[2]} {[3]} {[4]} {[5]}
Error using vertcat
Dimensions of arrays being concatenated are not consistent.
Error in test1 (line 12)
ArrCell2 = [ { new }; ArrCell ];

请先登录,再进行评论。

更多回答(2 个)

Image Analyst
Image Analyst 2015-12-18
But the big question is why are you even using a cell array for that instead of a simple numerical array. Cell arrays are complicated and use a huge amount of overhead. From what you've shown there is no reason to use one. I recommend this instead
Arr = [1,2,3,4,5];
Arr = [new, 1,2,3,4,5]
  1 个评论
Luis Isaac
Luis Isaac 2015-12-18
I using a cell array because ArrCell is composed of vectors and matrices of different sizes, i.e. size of [new] is different, or could be different, than [1]

请先登录,再进行评论。


Fletcher Garrison
编辑:Fletcher Garrison 2021-2-3
You can also use:
Arrcell = {1,2,3,4,5};
new = magic(5);
Arrcell = horzcat(new,Arrcell);

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by