Octave appending in a 2D cell array

11,384

Solution 1

It seems that you are confused with cell array indexing.

If you want to append elements at the end of a row in a matrix (in your case, a cell array), you must still make sure that all rows are of the same size after the assignment, otherwise you'll trigger an error about mismatching dimensions.

Instead of b(1) = {b(1, :), 2}, the following should work:

b(1, end + 1) = 2

Alternatively, if you want to append an entire column array of cells to b, use horizontal concatenation, for example:

b = [b, {2; 3; 4; 5; 6}];

This should append a single cell at the end of each row of b.

Solution 2

The reason the element gets inserted at [2, 2] and not [1, 1] is that by the time you try to insert the second element, the value denoted by end has increased from 0 to 1.

The following should do what you need:

>> b = cell(5, 0)

b = 

Empty cell array: 5-by-0

>> b(1,1) = {2}

b = 

    [2]
    []
    []
    []
    []

>> b(2,1) = {3}

b = 

    [2]
    [3]
    []
    []
    []

>> 
Share:
11,384
Rafi Kamal
Author by

Rafi Kamal

Updated on June 04, 2022

Comments

  • Rafi Kamal
    Rafi Kamal almost 2 years

    I'm trying to append an element at the end of a 2D cell array row. My code is:

    b = cell(5, 0)
    b(1) = {b(1, :), 2}   % Trying to append at the end of the first row
    

    This gives me the error: error: A(I) = X: X must have the same size as I

    I've also tried various other forms, such as:

    b = cell(5, 0)
    b(1, end+1) = 2   % Ok, inserts 2 at [1,1]
    b(2, end+1) = 3   % No, inserts 3 at [2,2] instead of [2, 1]