stored character string to character matrix by using loop
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
jarvan
am 13 Nov. 2014
Kommentiert: jarvan
am 15 Nov. 2014
I am going to use loop to prompt out 4 course name as 5-character string as form'AB101'. And I need to stored those string in a character matrix course.
n=4;
for i = 1:n
class{i} = input('Enter the course name : ','s')
mymat = [ 'myDataFile' str2num(class{:}) '.mat' ];
save(mymat);
end
str2num('class')
Here, I saved those 4 course by 4 mat file, however, how can I store in one file and switch them to a character matrix?
0 Kommentare
Akzeptierte Antwort
Geoff Hayes
am 14 Nov. 2014
Jarvan - you should avoid using class as a variable name since it conflicts with a MATLAB built-in function of the same name. Consider renaming it to * courseNames*. If you want to save all data to a single file, then try the following
n=4;
courseNames = cell(n,1); % pre-size classNames as a row vector
for k=1:n
courseNames{k} = input('Enter the course name : ','s');
end
% convert courseNames to a character matrix
courseNames = char(courseNames);
% write this variable to file
save('myCourseNames.mat','courseNames');
So we save all 4 course names to the same mat file.
With your code, the str2num(class{:}) probably generated an error (or at least it did for me on the second iteration of your loop). Converting a string that has characters to a number, for example str2num('AB101') would produce an empty matrix. And then, on the second iteration of the loop converting both column elements from class{:} would throw the
Error using str2num
Too many input arguments.
What were you attempting with this line of code?
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!