0
votes

Consider table in Matlab.

a = table(); 
a.c = 'a';

How can I add one row containing a string of different length to that table? i.e I want to get:

c  
______  

'a'     
'aa'

For example this simple attempt gives an error:

b = table(); 
b.c = 'aa';
result = [a; b] 

Error:

Could not concatenate the table variable 'c' using VERTCAT. Caused by: Error using vertcat Dimensions of matrices being concatenated are not consistent.

2
Simple arrays do not handle strings of different lengths. Try using cell arrays.Nivi
a = table(); a.c = {'a'; 'aa'} would do it, or a = table(); a.c = {'a'}; a.c(end+1,1)={'aa'}; to append to the endWolfie
@Wolfie Thank You very much ! It works ! Please convert a comment to answer - I will accept it. (I know the first way - a.c = {'a'; 'aa'} - but i my case I cannot use it since it is in loop and do not know {'a'; 'aa'} in advance, but the second way is OKAY ! )Alexander Chervov

2 Answers

1
votes

If you have an entire column of data, you can create a column from a cell array

tbl = table();
tbl.mycol = {'some text'; 
             'something else';
             'third item'};

If you want to append a single items (like in a loop) you could do

tbl = table();
mycell = {'some text'; 
          'something else';
          'third item'};
tbl.mycol = {};
for ii = 1:numel(mycell)
    tbl.mycol(ii) = mycell(ii);
end

Similarly, you can append to the end as you would an array

tbl.mycol(end+1) = {'fourth item'};

You can merge two tables by concatenating them using vertcat

myothercell = {'append this';
               '...and this'};
tbl1 = table();
tbl1.mycol = mycell;
tbl2 = table();
tbl2.mycol = myothercell;

tbl3 = vertcat(tbl1, tbl2);
2
votes

Due to how MATLAB's table objects treats the contained data, it tries to be smart with the data types. Occasionally when things try to be smart behind the scenes they get tripped up in ways that aren't necessarily readily apparent to the user.

What's happening here is that since your c column is created with a character array, MATLAB attempts to keep this column homogeneous and concatenate 'a' with 'aa'. This will error out due to MATLAB's handling of character arrays as matrices of characters, which comes with a size enforcement: all rows must have the same number of columns.

You have a couple options: use a string array (introduced in R2016b), or use a cell array. While string arrays are essentially cell arrays under the hood, they come with the advantage of dedicated string methods, allowing you to natively perform various string operations without needing to explicitly index into a cell array.

To change your code, simply use double quotes ("") instead of single quotes (''):

a = table(); 
a.c = "a";
b = table();
b.c = "aa";

T = [a;b]

Which returns:

T =

  2×1 table

     c  
    ____

    "a" 
    "aa"

Alternatively, you can explicitly force the type of c as a cell array:

a = table(); 
a.c = {'a'};
b = table();
b.c = 'aa';

T = [a; b]

Which returns the same.