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.

조회 수: 1 (최근 30일)
I tried using mod function but it doesn't work as my input contains Alphabet and numbers both.

채택된 답변

Paolo
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
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.
Stephen23
Stephen23 2018년 5월 28일
편집: Stephen23 2018년 5월 28일
@Paolo: instances of eval will hinder JIT optimization, so I suspect that efficiency might be the main reason for the documentation's advice to avoid str2num. This might be interested to you:

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Stephen23
Stephen23 2018년 5월 28일
편집: Stephen23 2018년 5월 28일
sscanf is probably the most efficient way to convert that char vector into a numeric:
>> sscanf('ABC 123','%*s %d')
ans = 123
  댓글 수: 3
Stephen23
Stephen23 2018년 5월 28일
편집: Stephen23 2018년 5월 28일
@Paolo: yes, the format string does need to be tailored to the actual expected strings, the exact format of which is something that Mazhar will have to clarify for us.
Mazhar
Mazhar 2018년 5월 28일
Well, I used the answer by @Paolo and it works perfectly fine for me. Thankyou guys.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품


릴리스

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by