elseif staement problem when matches a combination of string and number

1 view (last 30 days)
Hi,
I have a function returnes the folder name. It works very well for 'Al', 'Os' and 'Pt' but when I define 'O17' it gives me error. The "O" is a letter not a number.
Here is the error. Any idea how to resolve this? Thank you.
==================================
Arrays have incompatible sizes for this operation.
Error in returnFolderName (line 3)
if TagPerTab== 'Al' ; FolderName='Aluminum'
Error in ReacPenPlots5 (line 7)
FolderName=returnFolderName(TagPerTab)
=============================================
% Main code calling FolderName
TagPerTab= 'O17'
FolderName=returnFolderName(TagPerTab)
% The function
function FolderName=returnFolderName(TagPerTab)
if TagPerTab== 'Al' ; FolderName='Aluminum'
elseif TagPerTab== 'Os' ; FolderName='Osmium'
elseif TagPerTab== 'O17' ; FolderName='Oxygen' % gives error for this selection
elseif TagPerTab== 'Pt' ; FolderName='Platinum'
else
"The folder was not found. Enter a valid name"
end

Accepted Answer

Cris LaPierre
Cris LaPierre on 16 Aug 2022
Edited: Cris LaPierre on 16 Aug 2022
The error in this situation is coming from TagPerTab == 'A1'.When using the '==', it is comparing each character. When you do not have the same number of characters on the right and left of the equals signs, you get an error.
My suggestion would be to use strcmp instead.
if strcmp(TagPerTab,'A1')
FolderName='Aluminum';
elseif ...
...
end
This also might be a scenario to consider using a switch statement instead. Also, you must do something to display the error message if the file is not found (disp, warndlg, errordlg, etc).
% Main code calling FolderName
TagPerTab= 'O17'
TagPerTab = 'O17'
FolderName=returnFolderName(TagPerTab)
FolderName = 'Oxygen'
% The function
function FolderName=returnFolderName(TagPerTab)
switch TagPerTab
case 'Al'
FolderName='Aluminum';
case 'Os'
FolderName='Osmium';
case 'O17'
FolderName='Oxygen'; % gives error for this selection
case 'Pt'
FolderName='Platinum';
otherwise
warndlg("The folder was not found. Enter a valid name")
end
end

More Answers (0)

Categories

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

Tags

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!