Borrar filtros
Borrar filtros

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

2 visualizaciones (últimos 30 días)
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'));

Respuesta aceptada

Guillaume
Guillaume el 5 de Jun. de 2017
Editada: Guillaume el 5 de Jun. de 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 comentarios
Vetrichelvan Pugazendi
Vetrichelvan Pugazendi el 5 de Jun. de 2017
Is there a way to do same thing with matrices ? Instead of cell arrays ?
Guillaume
Guillaume el 5 de Jun. de 2017
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

Iniciar sesión para comentar.

Más respuestas (1)

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

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by