How can i make a dinamic row in a matrix or a cell?

1 view (last 30 days)
I have a slight problem concatenating a row from a certain array let's say:
%Normal Array
arr = [1,2,3;4,5,6];
%i want to encrease one row specific like this:
arr(1,:) = [arr(1,:), 7];
%I want this result:
arr => [1,2,3,7;4,5,6];
% but i still have this kind of error: "Error Unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side is 1-by-2."
% ¿how can i solve this please? I also tried with cells but i have the same error:
c = {1,2,3};
c = {c;{3,2,4,5}};
c(1,:) = {c,{4}};
Thank in advance.

Accepted Answer

the cyclist
the cyclist on 27 Nov 2021
Edited: the cyclist on 27 Nov 2021
In MATLAB, there cannot be an "empty" spot in a numerical array. So, you need to decide what you want in that spot. Sometimes a zero or a NaN can be a placeholder. So, you could do
arr = [1,2,3;4,5,6];
arr = [arr [7;NaN]]
arr = 2×4
1 2 3 7 4 5 6 NaN
Similarly, a cell array could have an empty array in one location
C = num2cell([1,2,3;4,5,6])
C = 2×3 cell array
{[1]} {[2]} {[3]} {[4]} {[5]} {[6]}
C = [C,{7;[]}]
C = 2×4 cell array
{[1]} {[2]} {[3]} {[ 7]} {[4]} {[5]} {[6]} {0×0 double}
  3 Comments
the cyclist
the cyclist on 28 Nov 2021
Edited: the cyclist on 28 Nov 2021
You need to think of this as adding a complete column. So, your syntax does not work, because it is trying to append "column" of three more elements only to the second row, which does not make sense.
The following will work to add one element to the second row, but leaving the other rows "empty":
arr = [1,2,3;4,5,6;7,8,9];
arr = [arr,[NaN; 77; NaN]]
arr = 3×4
1 2 3 NaN 4 5 6 77 7 8 9 NaN

Sign in to comment.

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!