In this article, we will discuss the “Reversing of a number” in MATLAB that can be done using the multiple methods which are illustrated below.
Using str2num()
The str2num() function is used to convert the specified character array or string to a numeric array.
Syntax: str2num(chr)
Parameters: This function accepts a parameter .
- char: This is the specified character array or string.
Example:
Output:
ans = 10
Using fliplr()
The fliplr() function is used to flip the specified number from left to right.
Syntax: fliplr(num)
Parameters: This function accepts a parameter.
- num: This is the specified number.
Example:
Output:
ans = 321
Using str2num(), fliplr(), and num2str()
The num2str() function is used to convert the specified numbers to a character array.
Syntax: num2str(num)
Parameters: This function accepts a parameter.
- num: This is the specified number.
Example:
Matlab
Number = 2468
Reversed_Number = str2num(fliplr(num2str(Number)))
|
Output:
Number = 2468
Reversed_Number = 8642
Using polyval( ) and num2str( )
The polyval(p, x) function is used to return the value of a polynomial of degree n evaluated at x. The input argument p is a vector of length n+1 whose elements are the coefficients in descending powers of the polynomial to be evaluated.
Syntax: polyval(p, x)
Parameters: This function accepts two parameters,
- p: This is the specified input vector of length n+1.
- x: This is the specified matrix or vector or array.
Matlab
Number = 3579
s = num2str(Number) - '0' ;
Reversed_Number = polyval(s( end :-1:1),10)
|
Output:
Number = 3579
Reversed_Number = 9753
Using flip( ) and sprintf()
The sprintf() function is used to format the data into a string or character vector.
Syntax: sprintf(formatSpec, A1, …, An)
Here, sprintf(formatSpec, A1, …, An) is used to format the data in arrays A1,…, An uses the formatting operators specified by formatSpec and returns the resulting text in str.
Example:
Matlab
Reversed_Number = flip(sprintf( '%d' , 5678), 2)
|
Output:
Reversed_Number = 8765
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
05 Aug, 2021
Like Article
Save Article