elseif staement problem when matches a combination of string and number
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Cris LaPierre
2022-8-16
编辑:Cris LaPierre
2022-8-16
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.
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'
FolderName=returnFolderName(TagPerTab)
% 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
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!