I am looking for a code to identify if the entered number is odd or even. For example: "ABC 123", I would be really grateful if someone shares the code.
5 ビュー (過去 30 日間)
古いコメントを表示
採用された回答
Paolo
2018 年 5 月 28 日
編集済み: Paolo
2018 年 5 月 28 日
You need to remove the characters before using mod function. You can use regexp to remove all non digits characters.
The following code uses regexp to match digits only in variable t , with the expression '\d' . The indices returned by regexp functions are used to get the digit values, before converting them to a number with num2str.
t = "ABC123";
t = char(t);
num = str2num(t(regexp(t,'\d')));
if(~mod(num,2))
disp('Number is even')
else
disp('Number is odd')
end
3 件のコメント
Paolo
2018 年 5 月 28 日
編集済み: Paolo
2018 年 5 月 28 日
Thank you Stephen. I did not know that str2num used eval, so thanks for pointing that out. I actually have already read that post of yours; it's really informative and well written.
That's true, Matlab always recommends using str2double, which is slightly counter-intuitive in my opinion because why would I need to convert to a double if I do not require the precision? I guess the reason is the eval call of str2num as you pointed out.
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!