Hi,
I want to reverse a number without using MATLAB functions "digitrevorder()" and "fliplr()". Please help. Thank you!

답변 (3개)

Evan
Evan 2014년 11월 18일

2 개 추천

x = 1234;
s = num2str(x) - '0';
xr = polyval(s(end:-1:1),10)

댓글 수: 7

Evan
Evan 2014년 11월 18일
Note that this answer is for a single number (scalar), not a vector.
John D'Errico
John D'Errico 2014년 11월 18일
편집: John D'Errico 2014년 11월 18일
+1
I suppose polyval works here, though I would not have approached it that way.
You could as easily have just used str2num, in which case polyval would be unnecessary, as well as the conversion from char to numeric in the middle by subtracting '0'.
A = 1234;
B = num2str(A);
B = str2num(B(end:-1:1))
B =
4321
There are often many ways to solve a problem in MATLAB, all of which are quite reasonable.
Evan
Evan 2014년 11월 18일
편집: Evan 2014년 11월 18일
Doh! I don't know what I was thinking! That's a much less convoluted way. I'm so used to having to use the polyval trick for CODY problems that I didn't even think about that. Thanks!
Image Analyst
Image Analyst 2014년 11월 18일
For what it's worth, I was thinking of John's method too (which he should have put as a separate answer so I could vote for it.)
Guillaume
Guillaume 2014년 11월 18일
I would think that since it looks very much like an assignment, the idea is to force the student to use a loop. There's certainly no point of disallowing fliplr if you allow any of the solutions presented here.
John D'Errico
John D'Errico 2014년 11월 18일
편집: John D'Errico 2014년 11월 18일
A moderately interesting question is to find a solution in one line, without needing to form an intermediate variable. (And without the application of fliplr!) Seems trivial with that function.
Guillaume
Guillaume 2014년 11월 18일
편집: Guillaume 2014년 11월 18일
You also want to disallow rot90, flipud and flip, otherwise it's also trivial.

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

Syed Haider
Syed Haider 2014년 11월 18일

0 개 추천

A = [1 2 3 4; 5 6 7 8];
y = A(:,end:-1:1)

댓글 수: 3

John D'Errico
John D'Errico 2014년 11월 18일
That reverses a vector or array of numbers, not the digits of a single number.
Syed Haider
Syed Haider 2014년 11월 18일
Yeah you are right :) I am sorry. Should i remove the answer? or may be it will be helpful for someone.
John D'Errico
John D'Errico 2014년 11월 18일
I don't see any reason to remove it.

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

saurabh jare
saurabh jare 2023년 3월 7일

0 개 추천

function ran=reverse_number(x)
%x=input('Enter the value for checking the palindromic= \n');
check=x;
ran=0;
while (check~=0)
ran=(ran*10)+mod(check,10);
check=fix(check/10);
end

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

질문:

2014년 11월 18일

답변:

2023년 3월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by