Info

This question is closed. Reopen it to edit or answer.

Having a hard time trying to transform this function in a for loop

1 view (last 30 days)
Guys, I made a code to transform decimal numbers into their binary form. I know that MATLAB have this function (dec2bin), but I had to write down my own code
I had to do this in two different ways: using a while loop and using a for loop
After days, I managed to make the code using while, but I'm just stucked in making the for one.
function bin=dec8(d)
i=1;
q=floor(d/2);
r=rem(d,2);
bin(i)=num2str(r(i));
while q>=2
d=q;
i=(i+1);
q=floor(d/2);
r=rem(d,2);
bin(i)=num2str(r);
end
bin(i+1)=num2str(q);
bin=fliplr(bin);
I have to make "q" go from (d/2) to 2 and correlates that with the vector sequence, but how?
  1 Comment
luc
luc on 4 Jun 2015
Hey Daniel!
This might be considered cheating the assignment but try the command
open dec2bin
and see if the code makes sense!

Answers (1)

Guillaume
Guillaume on 4 Jun 2015
Your while loop stops after you've divided the original number by 2 enough times to reach 0. To convert to a for loop you need to know before hand how many times that's going to be.
log2 will tell you that.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!