How to input name from the user using loop and simple input functions
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Vetrichelvan Pugazendi
am 5 Jun. 2017
Kommentiert: Guillaume
am 5 Jun. 2017
I had this question in my exam where i had to ask the user to input n number of strings based on the value of n the user enters. and this is what i did. It works but there are some errors. I would like to know why does it occur and what does it mean ? and how to rectify them?
%the exact coding
clc
n=input('Enter value of n ');
a=[];
for k=1:n
a(k,:)=char(input('Input String ','s'));
end;
and the error message along with output :
Enter value of n 2
Input String defgh
Input String nvd
Subscripted assignment dimension mismatch.
Error in file (line 5)
a(k,:)=char(input('Input String ','s'));
0 Kommentare
Akzeptierte Antwort
Guillaume
am 5 Jun. 2017
Bearbeitet: Guillaume
am 5 Jun. 2017
A matrix of characters, like any other matrix, must have the same numbers of columns for all the rows. Your first assignment to the matrix, at k = 1, sets the number of columns to the length of the input string. From then on, any assignment to any row of the matrix must have the exact same number of characters or you'll get a subscripted assignment mismatch.
The fix is to use cell arrays instead of matrices:
a = cell(n, 1);
for k = 1:n
a{k} = input('Input String ', 's'); %absolutely no need for char(...)
end
2 Kommentare
Guillaume
am 5 Jun. 2017
a = repmat(string, n, 1);
for k = 1:n
a[k] = input('Input String ', 's');
end
If you really want a char array you can convert the cell array into a char array after the loop:
a = cell(n, 1);
for k = 1:n
a{k} = input('Input String ', 's'); %absolutely no need for char(...)
end
a = char(a); %convert into a char vector
char will automatically pad the shorter char vectors.
Doing it in the loop is possible, but less efficient for no benefit:
a = []
for k = 1:n
a = char([a; {input('Input String ', 's')}]);
end
Weitere Antworten (1)
KSSV
am 5 Jun. 2017
n=input('Enter value of n ');
a=cell(n,1);
for k=1:n
a{k}=input('Input String ','s');
end
celldisp(a)
0 Kommentare
Siehe auch
Kategorien
Mehr zu Matrices and Arrays 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!