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

採用された回答

Cris LaPierre
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.
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 件のコメント
Birsen Ayaz-Maierhafer
Birsen Ayaz-Maierhafer 2022 年 8 月 16 日
編集済み: Birsen Ayaz-Maierhafer 2022 年 8 月 16 日
Chris,
Thank you. I used switch, case and otherwise and it resolved the issue.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by