Hi guys, i am new here. :) I have a problem with IF/Else statement, but only in GUI. If i put only one if statement, like this
if s=='Add'
f=x+y;
end
It works, but when i add this:
if s=='Add'
f=x+y;
end
if s=='Substract'
f=x-y;
end
It doesn't work.Also, if i only use
if s=='Substract'
f=x-y;
end
it works.I don't have a clue why is this happening.Any idea?

 Akzeptierte Antwort

Jan
Jan am 16 Mai 2017
Bearbeitet: Jan am 16 Mai 2017

0 Stimmen

There is not connection to the fact, that the code "runs in a GUI" - by the way: there is even nothing like "running in GUI". Code is code.
The problem is the comparison of a string the the == operator, which performs an elementwise comparison. If the compared strings have a different number of characters, such a comparison must fail.
Use strcmp instead:
if strcmp(s, 'Add')
f = x+y;
end
if strcmp(s, 'Substract')
f = x-y;
end
Or with switch/case:
switch s
case 'Add'
f = x+y;
case 'Subtract'
f = x-y;
otherwise % No SWITCH without OTHERWISE!
error('Unexpected value of [s]');
end
Note: In your question you write "doesn't work". Please post the complete error message in the future, because these messages contain valuable information to solve the problem.

Weitere Antworten (2)

jack int
jack int am 16 Mai 2017

0 Stimmen

Switch/case works, but i wanted to know why if/else doesn't. :P

1 Kommentar

Then please read my answer, where I explained the problem with using the == operator:
'test' == '1234'
This replies [false, false, false, false]. In the IF command you want a scalar condition. Therefore Matlab converts the expression internally to:
if all(s=='Add') && ~isempty(s=='Add')
Now try:
'test' == '123'
You get an error message, because an elementwise comparison is not working.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu MATLAB Report Generator finden Sie in Hilfe-Center und File Exchange

Tags

Gefragt:

am 16 Mai 2017

Beantwortet:

am 17 Mai 2017

Community Treasure Hunt

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

Start Hunting!

Translated by