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

 採用された回答

Stephen23
Stephen23 2017 年 6 月 8 日
編集済み: Stephen23 2017 年 6 月 8 日

1 投票

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 件のコメント

Kundera
Kundera 2017 年 6 月 8 日
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 2017 年 6 月 8 日
編集済み: Stephen23 2017 年 6 月 8 日
@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 2017 年 6 月 8 日
Thanks a lot @Stephen. I am a beginner, so much to learn :-)
Stephen23
Stephen23 2017 年 6 月 8 日
@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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeScope Variables and Generate Names についてさらに検索

質問済み:

2017 年 6 月 8 日

コメント済み:

2017 年 6 月 8 日

Community Treasure Hunt

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

Start Hunting!

Translated by