Problem with a function: to convert from base3 to base10
Show older comments

1 Comment
dpb
on 29 Mar 2021
No idea what you did to get the flashing display when you posted, but just attach the text of the window and any error messages...this is unreadable.
Answers (1)
For the future, please use the formatting tools available to you to paste formatted code. Don't post pictures of code. Nobody can run a picture of code, least of all a flashing picture of code that mysteriously disappears and is replaced by an incorrectly rotated error message.
Your function works at a basic level, but it has problems. It does not guard against invalid inputs (e.g. 546 is not a valid base-3 number). Avoid using while loops to blindly chew at numbers if you can precalculate the number of iterations beforehand. My guess is that you fed the function a negative number and the while loop just kept going until it ate all the available memory.
Long story short: sanitize your inputs and don't use while loops unnecessarily. The whole thing simplifies anyway.
num3=min(max(num3,0),2);
x=num3;
% this will get the number of digits for reasonably sized integers
nt=numel(num2str(fix(abs(num3))));
num10=0;
for a=1:nt
num10=num10+mod(x,10)*3^(a-1);
x=floor(x/10);
end
[base2dec(num2str(num3),3) num10]
If you don't need to make this function as an exercise or challenge, you can always use base2dec().
a=base2dec('22',3);
gives
a =
8
3 Comments
Teresa Perdicoulis
on 1 Apr 2021
Teresa Perdicoulis
on 1 Apr 2021
Teresa Perdicoulis
on 1 Apr 2021
Categories
Find more on Simulink in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!