how can I break up a number into its separate digits

64 ビュー (過去 30 日間)
Michael
Michael 2022 年 1 月 28 日
編集済み: DGM 2022 年 1 月 28 日
how can I break up a number say ABCD into its components, A, B , C and D?
Would I use floor, ceil, or fix? or maybe another command?
  2 件のコメント
Stephen23
Stephen23 2022 年 1 月 28 日
The MATLAB approach:
num = 5432
num = 5432
dgt = num2str(num)-'0'
dgt = 1×4
5 4 3 2
DGM
DGM 2022 年 1 月 28 日
I knew I was going to kick myself for not remembering that. It's like I can predict the future or something.

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

採用された回答

DGM
DGM 2022 年 1 月 28 日
編集済み: DGM 2022 年 1 月 28 日
I'm sure I've seen more elegant ways, but off the top of my head, I don't remember. EDIT: ... oh.
I'm assuming we're talking about integers. You'll have to decide how you want to handle negative numbers. If you want the outputs to carry the sign of the input, you can do that:
a = -123456;
% a fairly straightforward way using text
b1 = sign(a)*str2double(num2cell(num2str(abs(a)).')).'
b1 = 1×6
-1 -2 -3 -4 -5 -6
% Stephen's comment above with sign-handling
b2 = num2str(a)-'0';
b2 = sign(a)*b2(b2~=-3)
b2 = 1×6
-1 -2 -3 -4 -5 -6
% a mathematical approach is instructive, and can be done with a loop
ndigits = max(floor(log10(abs(a)))+1,1);
b3 = zeros(1,ndigits);
aa = a;
for d = ndigits:-1:1
b3(d) = rem(aa,10);
aa = fix(aa/10);
end
b3
b3 = 1×6
-1 -2 -3 -4 -5 -6
% but even then, the loop isn't necessary
b4 = rem(fix(a./10.^(fix(log10(abs(a))):-1:0)),10)
b4 = 1×6
-1 -2 -3 -4 -5 -6
  3 件のコメント
DGM
DGM 2022 年 1 月 28 日
編集済み: DGM 2022 年 1 月 28 日
What you have there is conceptually similar to the loop example. The behavior of mod() and rem() differ when considering negative numbers. Similarly, floor() and fix() differ when considering negative numbers. For positive integers, they would've been the same.
In practice, you'd want to avoid having separate named variables for each output, and generally you have no assurances of how many digits there will be. Using the loop and storing the output in a vector takes care of that. If you're only going to extract a certain handful of digits, then you might decide to define ndigits as a constant. That said, you would still probably want to make sure there are at least that many digits in the number.
Michael
Michael 2022 年 1 月 28 日
Thank you.
I was told to have multiple outputs so that is why I used them. We haven't learned very many commands. Fix, floor, ceil, mod. And the basic operators.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by