Decomposition in any base Matlab
조회 수: 9 (최근 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에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!