Effacer les filtres
Effacer les filtres

elseif staement problem when matches a combination of string and number

1 vue (au cours des 30 derniers jours)
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

Réponse acceptée

Cris LaPierre
Cris LaPierre le 16 Août 2022
Modifié(e) : Cris LaPierre le 16 Août 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
  1 commentaire
Birsen Ayaz-Maierhafer
Birsen Ayaz-Maierhafer le 16 Août 2022
Modifié(e) : Birsen Ayaz-Maierhafer le 16 Août 2022
Chris,
Thank you. I used switch, case and otherwise and it resolved the issue.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by