How to insert char to table?

조회 수: 50 (최근 30일)
Emmanouil Barmpounakis
Emmanouil Barmpounakis 2015년 9월 24일
답변: Peter Perkins 2015년 9월 24일
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?

답변 (2개)

Muthu Annamalai
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

Peter Perkins
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.

카테고리

Help CenterFile Exchange에서 LaTeX에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by