How to input name from the user using loop and simple input functions

2 次查看(过去 30 天)
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'));

采纳的回答

Guillaume
Guillaume 2017-6-5
编辑:Guillaume 2017-6-5
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 个评论
Guillaume
Guillaume 2017-6-5
If you're on R2016b or later, you can use a string array:
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

请先登录,再进行评论。

更多回答(1 个)

KSSV
KSSV 2017-6-5
n=input('Enter value of n ');
a=cell(n,1);
for k=1:n
a{k}=input('Input String ','s');
end
celldisp(a)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by