필터 지우기
필터 지우기

Need help with leading zeroes being eaten in my function

조회 수: 7 (최근 30일)
Tony
Tony 2014년 4월 29일
답변: Tony 2014년 4월 30일
I have a function that re arranges digits of a number and then subtracts them, but if the number is a single digit, I want it to include the leading zero with it. Example: say I plugged in the number 09. My function should take 09, turn it into 90, then subtract 09. Instead, it does not see the zero and does 9-9 = 0.

채택된 답변

the cyclist
the cyclist 2014년 4월 29일
This is a bit awkward, but maybe you can improve it:
n = 9;
str2num(regexprep(fliplr(sprintf('%2d',n)),' ','0'))
This does the following:
  • The sprintf command creates a length-two string (with space if necessary for the missing digit)
  • fliplr() flips it
  • regexprep replaces the space (if there is one) with a zero
  • str2num converts it to a number
  댓글 수: 1
Kelly Kearney
Kelly Kearney 2014년 4월 29일
Or to skip the regexp step, use a formatting string that pads with 0s:
a = 9;
str2num(fliplr(num2str(a, '%02d'))) - a

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

추가 답변 (2개)

dpb
dpb 2014년 4월 29일
편집: dpb 2014년 4월 29일
If you read the value as numeric, internal storage is what it is; there are no "leading zeros". The only way you can do something like this is by keeping the string representation and reversing it before doing the numerical operations.
SOTOO--
>> in='09'
in =
09
>> res=str2num(fliplr(in))-9 % result as numeric
res =
81
>> res=num2str(str2num(fliplr(in))-9) % result as string
res =
81
>>
ADDENDUM:
NB: In your invocation, despite entering '09' it's automagically converted to internal numeric representation. You would have to either enter as a string (using the ' ' to surround the value) or use input or similar to get the input and leave it as string (the optional 's' argument).
Or, to make your current work, you could change to sotoo...
>> in=09
in =
9
>> res=str2num(fliplr(num2str(in,'%2.2d')))-9
res =
81
>>
You'll need to make the field width dynamic depending on the size of the input value and how many leading zeros you wish as that will predicate the actual value in the end.
Unfortunately, you can't count the leading zeros a user typed in if you don't save the input as string to begin with--they're not significant in parsing and so are discarded.

Tony
Tony 2014년 4월 30일
Thanks guys, give me a few days to work with these methods and I will get back to you soon.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by