trouble translating pseudo code for decimal number to base b
2 views (last 30 days)
Show older comments
I was given the following pseudo code however because of matlabs arrays starting at 1 and other issues im running into i cant really translate it and its really confusing.
I managed to translate the "base(z,b)" properly which translates an int to a base b number.
I cant really get behind why some indices are -k. the output doesnt really make much sense either.
Pseudocode:
decimaltobase(z,b):
nums = base(z,b);
r[0] = z - floor(z);
k = 0;
period = 0;
while period == 0 && r[k] != 0:
k = k + 1;
r[k] = b * r[k - 1];
z[-k] = r[k] - z[-k];
if r[k] == r[p] for any p < k:
period = 1;
store p;
if rk == 0:
return nums;
else:
return nums "." r;
my code:
function y = decimaltobase(z,b)
nums = base(floor(z),b);
r(1) = z - floor(z);
k = 1;
period = 1;
while period == 1 && r(k) ~= 0
k = k + 1;
r(k) = b * r(k - 1);
z(k) = floor(r(k));
r(k) = r(k) - z(k);
pfound = false;
if pfound == false
p = 1;
end
while p < k
disp(p)
disp(k)
if r(k) == r(p)
period = 1;
pfound = true;
else
p = p + 1;
end
end
end
y = horzcat(nums,".",r);
end
2 Comments
Stephen23
on 10 Aug 2022
Edited: Stephen23
on 10 Aug 2022
That does not look like pseudo-code, it looks like Python code. In which case [-1] is the last element in an iterable, and [-k] is the k-th last element. To do something similar in MATLAB you would use END.
Rather than reinventing the wheel, you might like to consider using John D'Errico's excellent fex contribution:
Answers (0)
See Also
Categories
Find more on Logical 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!