how do i get the the fifth and fourth number form behind?
조회 수: 1 (최근 30일)
이전 댓글 표시
Hello everybody. I would like to know how to extract the fifth and fourth number form behind?
if x = [2361273621, 2937812378, 2367823827]
the output should be [ 73, 12, 23]
댓글 수: 0
답변 (2개)
John D'Errico
2022년 10월 8일
편집: John D'Errico
2022년 10월 8일
You want the 5th and 4 decimal digits of the numbers, as a 2 digit number? Surely this is homework. But since you already have an answer...
The answer is simple enough though. But you need to consider that IF the 5th digit from the right was a ZERO, then the result will NOT be a decimal number that starts with a zero. So I've included some extra test cases that will have zeros in those positions. ALWAYS test your code, to insure it will work on cases that stress the algorithms.
x = [2361273621, 2937812378, 2367823827, 1234507824, 1111112230222, 99999900111];
% first, strip off the high order decimal digits. Do you see this can be
% done using rem?
x54321 = rem(x,100000)
% Next, strip off the lower order digits, and at the same time, dividing by
% 1000
x54 = floor(x54321/1000)
So you see this must always work? In fact, we can write the entire computation in one simple line of code.
x54 = floor(mod(x,100000)/1000)
The trick is to isolate the desired digits. I did that using first a mod, then a divide, then a floor. Again though, note that in the last three cases, the numbers do not have a leading 0 digit, and certainly not so in the case where both digits were 0. We can recover the leading zeros, IF we are willing to represent the numbers in a character form.
dec2base(x54,10)
But they are NOT numbers, but chacracter representations of those numbers. Or, we could do this:
dec2base(x54,10) - '0'
Here, each row of the resulting array is now one of the desired decimal digits.
A nice thing about the above scheme (in any form) is it even works on small numbers, so it would work on the number 123, and then return the result as all zeros.
Are there alrternative schemes? Of course. Consider this one:
y54 = dec2base(x,10,5)
y54 = y54(:,end - [4 3])
I carefully extracted only the desired columns.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!