How to insert char to table?

68 visualizzazioni (ultimi 30 giorni)
Emmanouil Barmpounakis
Emmanouil Barmpounakis il 24 Set 2015
Risposto: Peter Perkins il 24 Set 2015
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?

Risposte (2)

Muthu Annamalai
Muthu Annamalai il 24 Set 2015
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

Peter Perkins
Peter Perkins il 24 Set 2015
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.

Categorie

Scopri di più su Data Type Conversion in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by