フィルターのクリア

Create a loop with doubling the previous number minus 1

1 回表示 (過去 30 日間)
Sergio
Sergio 2024 年 1 月 17 日
コメント済み: Sergio 2024 年 1 月 17 日
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

採用された回答

Hassaan
Hassaan 2024 年 1 月 17 日
% Initialize the starting number
number = 2;
% Loop until the number exceeds 66
while number <= 66
disp(number);
number = number * 2 - 1; % Multiply by 2 and subtract 1
end
2 3 5 9 17 33 65
When you run this MATLAB script, it will display the sequence of numbers as per your specified rule, stopping when the next number would exceed 66.
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Feel free to contact me.

その他の回答 (1 件)

Dyuman Joshi
Dyuman Joshi 2024 年 1 月 17 日
編集済み: Dyuman Joshi 2024 年 1 月 17 日
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
2 3 5 9 17 33 65
If you are new to MATLAB, I suggest you take the free MATLAB Onramp tutorial to learn the syntax and essentials of MATLAB.
  1 件のコメント
Sergio
Sergio 2024 年 1 月 17 日
Thanks for the tip, I will certainly look at that tutorial!!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeIntroduction to Installation and Licensing についてさらに検索

タグ

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by