Borrar filtros
Borrar filtros

elseif staement problem when matches a combination of string and number

1 visualización (últimos 30 días)
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

Respuesta aceptada

Cris LaPierre
Cris LaPierre el 16 de Ag. de 2022
Editada: Cris LaPierre el 16 de Ag. de 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

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by