MATLAB Answers

How to break and integer into an array output.

274 ビュー (過去 30 日間)
hello world
hello world 2014 年 12 月 1 日
コメント済み: Walter Roberson 2018 年 9 月 30 日
I need to build a function that turns an inputted integer into an array. An example is inputInteger = 9876 solution_array = [9 8 7 6] I have a code that works, however, I need it to work without the use of most built-in functions such as mod and possibly even floor. I can however use numel and zeros.
This is the code I have so far:
function solution_array = breakN2digits(inputInteger)
digits =floor(log10(inputInteger)) + 1;
if inputInteger >= 0
solution_array = zeros();
for i=digits:-1:1
solution_array(1,digits+1-i) = floor(inputInteger/(10^(i-1)));
inputInteger = mod(inputInteger,10^(i-1));
end
end
end

  0 件のコメント

サインインしてコメントする。

回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 12 月 1 日
a=9876;
b=num2str(a)-'0'

  2 件のコメント

Hayat Ullah Kakakhel
Hayat Ullah Kakakhel 2018 年 9 月 30 日
wow, it perfectly works,,, But don't know what is the logic behind
b=num2str(a)-'0'
will you please explain?? Thanks
Walter Roberson
Walter Roberson 2018 年 9 月 30 日
The very first electronic character sets were created based upon purely mechanical concerns about rotation of the appropriate parts. However, once people started to get together to try to standardize character sets, one of the very first things they agreed upon was that no matter what the actual numeric values were to be associated with the digits, that they were to be arranged in consecutive order, '0', '1', ... up to '9' .
Because this ordering property has been guaranteed for decades, you can always convert the character for a digit into the numeric value for the digit by finding the relative position of the digit character to the character for '0', which is easily done by subtracting off the representation of '0' from the representation of the digit character.

サインインしてコメントする。


Pratik Bajaria
Pratik Bajaria 2014 年 12 月 1 日
Hello,
One of the easiest way to do this is fooling the way around.
First convert the number into string. Then run a simple for loop to attain every character, and then finally convert them back to number at the time of allocation.
A simple code to the above algorithm is as shown below.
x=9876;
xstr=num2str(x);
xarray=zeros(1,numel(xstr));
for i=1:numel(xstr)
xarray(i)=str2num(xstr(i));
end
Please let me know in case of any doubts.
Regards, Pratik

  1 件のコメント

hello world
hello world 2014 年 12 月 1 日
Cannot use built-in function such as num2str

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by