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

 Accepted Answer

Stephen23
Stephen23 on 8 Jun 2017
Edited: Stephen23 on 8 Jun 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 Comments

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.
@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:
Thanks a lot @Stephen. I am a beginner, so much to learn :-)
@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.

Sign in to comment.

More Answers (0)

Categories

Find more on Scope Variables and Generate Names in Help Center and File Exchange

Asked:

on 8 Jun 2017

Commented:

on 8 Jun 2017

Community Treasure Hunt

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

Start Hunting!