Decomposition in any base Matlab
7 ビュー (過去 30 日間)
古いコメントを表示
Hi, I would like to know if there was a Matlab builtin function that decompose any integer in a chosen base, it would be something like:
dec2base(52,4)
ans =
0 1 3
I've write my own function, but it's pretty slow. Maybe you will detect an error in my code (nVariable is the length of the array I want my function to return):
function [digits] = LeftDecompose(number, base, nVariable)
% Decompose a number in any base.
quotient = floor(number/base^(nVariable-1));
remainder = number - quotient * base^(nVariable-1);
if remainder == 0
digits = [zeros(1, nVariable-1) quotient];
else
digits = [LeftDecompose(remainder, base, nVariable - 1) quotient];
end
end
Thank you in advance.
0 件のコメント
採用された回答
David Sanchez
2013 年 7 月 18 日
I don't know whether you checked it out or not, but dec2base is a MATLAB built-in function. Type the following in the command window for all the details:
help dec2base
doc dec2base
6 件のコメント
Cedric
2013 年 7 月 19 日
編集済み: Cedric
2013 年 7 月 19 日
It returns a cell array of strings, because DEC2BASE itself returns strings (more accurately char arrays):
>> ret = dec2base(54, 4)
ret =
312
>> class(ret)
ans =
char
ARRAYFUN itself does nothing else than to apply the function given as a first argument to values of arrays given as additional arguments, and output "some" array with the result. When the function (given as a 1st argument) outputs scalars, ARRAYFUN outputs a regular numeric array. When the function outputs arrays, we have to tell ARRAYFUN that it can generate a non uniform output (see last two args), which it does in a cell array.
You can then convert these strings to numbers using e.g. STR2DOUBLE on the whole cell array. To illustrate based on the first example above:
>> class(my_array_base4) % Check that output is a cell array.
ans =
cell
>> class(my_array_base4{1}) % Check that cells content is char/string.
ans =
char
>> values = str2double(my_array_base4) % Convert to double.
values =
302 303 310 311 312 313 320
>> class(values) % Check that it's double
ans =
double
BUT! these are base 10 numbers and there are not a lot of good reasons to convert back to double. In fact, DEC2BASE provides you with a representation of a decimal number into a certain base. The purpose is display or storage, for which strings are well adapted. MATLAB won't compute in base 4 for example and if you want to perform computations, you do it in base 10 first and you convert the result to a base 4 representation afterwards.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!