How to insert char to table?
    30 次查看(过去 30 天)
  
       显示 更早的评论
    
I am trying to insert a char variable into the first column named 'Trip' of a Table titled 'Out2'. All the other columns contain numerical values, which appear just fine using
Out2(k,2)={varName}
However, when I try to insert variable filename an error appears.

I am writing the following code
Out2(k,1)= {filename};
and the following error appears:
Subscripted assignment dimension mismatch for table variable 'Trip'.
What is the correct way to insert char into a table?
0 个评论
回答(2 个)
  Muthu Annamalai
    
 2015-9-24
        If you are mismatching to the number of rows in your Table.
Try assigning a cell-array of strings to your Table out2, at the column 'Trip'. To do this use strsplit function along with fileread
Then when you do,
   new_values = strsplit(fileread('data.txt'));
   Out2.Trip = new_values;
However it may also be you only want to replace the first element of the column Trip, then you can do the following,
Out2.Trip(1) = fileread(filename);
HTH.
-Muthu
0 个评论
  Peter Perkins
    
 2015-9-24
        Emmanouil, it's pretty hard to answer this for sure without more info. But assuming that you have a table like this
>> out2 = table({'a'; 'bb'; 'ccc'},[1;2;3],'VariableNames',{'Trip' 'X'})
out2 = 
    Trip     X
    _____    _
    'a'      1
    'bb'     2
    'ccc'    3
and a string like this
>> filename = 'abcdefghij';
>> whos filename
  Name          Size            Bytes  Class    Attributes
  filename      1x10               20  char
then the best way to assign that string into an element of the Trip variable is like this:
>> out2.Trip{2} = filename
out2 = 
        Trip        X
    ____________    _
    'a'             1
    'abcdefghij'    2
    'ccc'           3
Notice that Trip is a cell array containing strings, and so the left-hand side of that assignment first picks out Trip, as out2.Trip, and then assigns into it using braces.
If Trip in your table is a char matrix (which isn't really a great way to store strings), then you'd do something like
out2.Trip(2,:) = filename
Hope this helps.
0 个评论
另请参阅
类别
				在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
			
	产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


