How can I make an if statement based on the answer of an input?
17 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Ayaan
am 16 Nov. 2025 um 19:39
Kommentiert: Ayaan
am 16 Nov. 2025 um 20:50
I want to make an if statement based on what stat a user types in their input, in this case founding year, but I keep on running into errors
chosenstat = input("What statistic would you like to view? ")
if chosenstat == "Founding year"
fprintf("1968")
end
0 Kommentare
Akzeptierte Antwort
dpb
am 16 Nov. 2025 um 20:23
Couple of issues here. As the documentation for input shows, the form as you've written it tries to evaluate the user input as a MATLAB expression including references to any defined variables in the workspace. This is pretty powerful, but can also lead to a lot of confusion, particularly with neophyte users not well-versed in MATLAB syntax and maybe not familiar with the content of the workspace when running the code.
To input a string as your code is expecting, you need the alternative form as
chosenstat = input("What statistic would you like to view? ",'S')
where the 'S' second parameter is the flag to tell MATLAB that the input is to be read as a text and no evaluation of that text is done.
It's not possible to run code in this environment because interactive i/o isn't supported, but in a local session,
>> chosenstat = input("What statistic would you like to view? ",'s')
What statistic would you like to view? Founding year
chosenstat =
'Founding year'
>> chosenstat == "Founding year"
ans =
logical
1
>>
will work.
I think the above would be a very painful user interface to use, however; any typo or other issue will fail to match and it's a lot of typing to ask for, anyway. I would suggest this might be the place for a user dialog dropdown instead so the user can pick from the available choices and those can be constrained to only be those your app is capable of handling, removing all the other error checking code you would have to have, otherwise.
Experiment with something like
>> OPTIONS={'Founding year','Founding member','Other Option'};
>> hUIF=uifigure;
>> hDD=uidropdown(hUIF,'Items',OPTIONS);
>> hDD.Value
ans =
'Founding member'
>>
where I selected the second element and so the returned value is then the 'Founding member' string.
I would then also suggest that a switch, case, otherwise construct would be the way to pick the code to execute based on the user selection--
switch hDD.Value
case OPTIONS{1} % Founding year code
...
case OPTIONS{2} % Founding member code
...
case OPTIONS{3} % etc., ...
...
otherwise % if user did something else
...
end
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Number Theory finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!