If I want to add the previous 3 terms in a sequence how would I do it?

4 views (last 30 days)
Say for example the sequence results in 0, 1, 2, 3, 6, 11, ...

Accepted Answer

Ameer Hamza
Ameer Hamza on 28 Sep 2020
Just write down in MATLAB what you described in words. The syntax is pretty intuitive
n = 10; % number of terms
x = zeros(1, n);
x(1:3) = [0 1 2]; % initial terms
for i = 4:n
x(i) = sum(x(i-3:i-1));
end
  3 Comments
Ameer Hamza
Ameer Hamza on 28 Sep 2020
Edited: Ameer Hamza on 28 Sep 2020
No, I fixed the value at 10. You can also use input() function in my code. The logic of both codes is basically the same.
n = input('enter the number of terms desired: ');
x = zeros(1, n);
x(1:3) = [0 1 2]; % initial terms
for i = 4:n
x(i) = sum(x(i-3:i-1));
end
Ameer Hamza
Ameer Hamza on 28 Sep 2020
But then the preallocation will be gone, which is usually a recommended practice.

Sign in to comment.

More Answers (0)

Categories

Find more on Startup and Shutdown 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!