How can I get a prompt to repeat for a user given input?

4 views (last 30 days)
Hello!
I'm pretty new to MATLAB, and I was wondering how to write a code that would repeat a prompt and save each answer to a new variable.
For example, I want the user to answer the question 'How many states are you going to?' using the prompt:
states = inputdlg('How many states are you going to?');
states = str2num(states{:});
I then want the question 'How many days are you spending in state 1?' to come up using:
days(1)= inputdlg('How many days are you spending in state (1)?');
Which would repeat for state 1: states. Im using the answer from the number of days per state further along in the code to later get a total amount of money spent, which I can figure out. I'm just a little stuck here.
Thanks!

Answers (1)

bio lim
bio lim on 6 Jul 2015
Edited: bio lim on 15 Jul 2015
Hi, Liz. I think you should use sprintf.
states = inputdlg('How many states are you going to?');
states = str2num(states{:});
for i = 1 : states
st = sprintf('How many days are you spending in state %d?', i);
days(i) = inputdlg(st)
end
For example, I put my states as 3 and days as 1, 2 and 4.
days =
'1' '2' '4'
To access the element,
days(1)
ans =
'1'
Hope it helps.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!