0

I am writing a function in Matlab that converts a decimal number to binary and every time I try to run it, it tells me that I am in a infinite loop. Please help! This is my function :

function y = toBinary(x)
f = 1; 
r=0;
persistent y;

if x==0;
y=0;

else 
r = mod(x,2);
y = y+(r*f);
f = f*10;
y = toBinary (x/2);
end
save toBinary 

"x" is the decimal number we input;

"y" is the binary output;

"r" is the remainder;

"f" is the factor

Thank you in advance!

Karen N.
  • 19
  • 1

1 Answers1

0

You should do toBinary(floor(x/2)). Otherwise, you will end up with values after the decimal point.

Lazarus
  • 358
  • 1
  • 8