Create a loop with doubling the previous number minus 1
Show older comments
Hi, I have to make this loop:
2
3
5
9
17
33
65
which is the first number multiplied by 2 and subtract 1, then double the outcome of that, and subtract 1 and so on, until 66.
I made the following, however it outputs an addition instead of a multiplication of the previous number. How can I instruct this simple command to multiply by two and subtract 1 to the previous number, and stop at 66?
Thanks
for i = 2:3:66
fprintf('%d ',i)
end
Accepted Answer
More Answers (1)
Dyuman Joshi
on 17 Jan 2024
Edited: Dyuman Joshi
on 17 Jan 2024
Use a while loop and perform the operation in each iteration -
%Starting value
x = 2;
%Run the loop till the value of x is less than 66
while x<66
%Display the value first
disp(x)
%Modify the value as required and re-assign it to x
x = 2*x-1;
end
If you are new to MATLAB, I suggest you take the free MATLAB Onramp tutorial to learn the syntax and essentials of MATLAB.
Categories
Find more on MATLAB 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!