How to use an if statement with isempty(strfind()) as a condition?

So I have this code where I need to calculate taxes over a salary entered by the subject. This subject may enter any Province marked by abbreviations such as 'ON', 'AB' and 'PE' and they are put in a cell array called B. I do not understand why even if i do not enter the said Province, MATLAB does execute this if statement and thus calculate taxes for every Province. Do you guys have a solution so the said code does not execute?
Note : This is only part of a code, the rest of it is pretty much a copy of this code only with the 'ON' changed for another Province string. There is also no error shown, the program only executes all of it and displays it.
EDIT : I did join my .m file, according to Star Strider's comment
W = isempty(strfind(B,'ON'));
if W
if Salary <= 36848
ON = 0.0605*Salary;
elseif 36848.01 <= Salary & Salary <= 73698
ON = 0.0915*Salary;
elseif Salaire > 73698
ON = 0.1116*Salary;
end
fprintf('%.2f en Ontario\n',ON)
end
Thank you all,
tl dr : MATLAB executes the program even if the cell does not contain what it has to find to execute.

 Risposta accettata

If you don’t enter a province, the isempty condition will be true. Using the logical negation (~) in the ‘W’ assignment would seem to be the correct logic:
B = {'ON', 'AB' 'PE'};
W = ~isempty(strfind(B,'ON'));
if W
fprintf(1, '\nCalculate Ontario taxes\n')
end

5 Commenti

As Star's said, your logic is inverted. Your code will execute except if the string entered contains 'ON'.
Furthermore are you really sure you want to use strfind meaning that the 'ON' can be anywhere in the input string? For example, if the user enters 'LABRADOR', he'll get the 'AB' resulss.
Well actually since the user input can only contain the abbreviations : 'AB','PE','ON','NB' it cannot find anything else than what is exactly asked in this case. Please do refer, if you have the time to do so, to the dropbox link i have just made containing the program file : https://www.dropbox.com/s/0qfzuai432zz42y/Taxes_Calculator_MATLAB.m?dl=0
Thank you
Most of us here (I include myself) do not access files unless they are uploaded to MATLAB Answers. To upload your file, use the ‘paperclip’ icon, and complete both the ‘Choose file’ and ‘Attach file’ steps.
if strcmpi(B,'ON')
... do whatever for Ontario
end
Or
switch upper(B)
case 'ON':
... ontario
case 'MB':
... manitoba
end
Thank you Walter!
I was able to find the solution to my problem with your comment. Also thanks to the rest of you who commented, your comments were all as valuable. It's my first time posting here, so I didn't know how to link a file and all.

Accedi per commentare.

Più risposte (0)

Categorie

Community Treasure Hunt

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

Start Hunting!

Translated by