Info

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

Which loop do i use, loop or while. and how exactly would i use it?

1 view (last 30 days)
I need to make an array where
h(1)= v/2
h(2)= floor(h(1,1))/2
h(3)= floor(h(1,2))/2
and on continuously until h(unknown)<0.5 "v" is a random variable that will be entered
so is it possible to make a loop that leaves the answer of each one of these in the h array, then
bin=([h-floor(h)].*2)
bin array should only be made of 1s and 0s

Answers (1)

Star Strider
Star Strider on 6 Oct 2015
Either would work, but a while loop is probably more efficient in your application:
v = 10; % Create Data To Test Code
h(1) = v/2;
k1 = 2;
while h(end) >= 0.5
h(k1) = h(end)/2;
k1 = k1 + 1;
end
bin = [h-floor(h)]*2;
  2 Comments
DavHor
DavHor on 6 Oct 2015
unfortunately this does not "floor" the answer before dividing again eg. 45/2=22.5 22/2=11 11/2=5.5 5/2=2.5 2/2=1
see how the answers are always 0.5 or 0
the code doesn't work out right if 45/2=22.5 22.5/2=11.25 11.25/2=5.625 etc
Star Strider
Star Strider on 6 Oct 2015
I forgot to put the floor call in the loop:
v = 45; % Create Data To Test Code
h(1) = v/2;
k1 = 2;
while h(end) >= 0.5
h(k1) = floor(h(end))/2;
k1 = k1 + 1;
end
bin = [h-floor(h)]*2;
bin =
1 0 1 1 0 1 0

Community Treasure Hunt

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

Start Hunting!