Store a variable from prompt user input

Hi, I have this function which display a request in the prompt and asks user to input a number. The function then repeats until user inputs a valid number.
function num = inputNumber(prompt)
while true
num = str2double(input('Write your age :', 's'));
if ~isnan(num)
break;
end
end
I want then to store the input in the variable num but it is not happening. Why? How can I solve it? Thanks

 Respuesta aceptada

Stephen23
Stephen23 el 8 de Jun. de 2017
Editada: Stephen23 el 8 de Jun. de 2017
I changed it so that there is a limit to how many attempts can be made, and also that the output is always defined:
function out = inputNumber(prompt)
out = NaN;
tot = 3; % how many attempts to make
while isnan(out) && tot>0
out = str2double(input('Write your age :', 's'));
tot = tot-1;
end
end
and tested:
>> num = inputNumber()
Write your age: 64
num = 64

4 comentarios

Kundera
Kundera el 8 de Jun. de 2017
In that sense it works. But I was expecting (or at least, what I would like) to then have in the workspace a variable num with the value the user has inserted.
Stephen23
Stephen23 el 8 de Jun. de 2017
Editada: Stephen23 el 8 de Jun. de 2017
@Kundera: the variables inside a specific workspace have nothing to do with the variables in another workspace (e.g. the base workspace). MATLAB does not magically transport/show/distribute/... variables from inside one workspace into another workspace (and this would be very bad program design if it did: workspaces should be independent, and their variables should not magically appear elsewhere). It is your task to allocate them to output variables, if that is what you need to do.
All you need to do is assign the output to a variable of your choosing when you call it:
num = inputNumber()
You should work through the introductory tutorials, which explain these very basic MATLAB concepts:
You should also read about workspaces and how they are independent from each other unless you explicitly pass data between them:
and also read this:
Kundera
Kundera el 8 de Jun. de 2017
Thanks a lot @Stephen. I am a beginner, so much to learn :-)
Stephen23
Stephen23 el 8 de Jun. de 2017
@Kundera: my pleasure. Please do read the links that I gave.
You should accept the answer that best resolves your original question. Accepting answers is an easy way for you to show your thanks for us volunteers.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Scope Variables and Generate Names en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 8 de Jun. de 2017

Comentada:

el 8 de Jun. de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by