필터 지우기
필터 지우기

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
Vetrichelvan Pugazendi
Vetrichelvan Pugazendi 2017년 6월 5일
Is there a way to do same thing with matrices ? Instead of cell arrays ?
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