MATLAB Answers

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

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

  0 Comments

Sign in to comment.

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

Cesar Valencia
Cesar Valencia on 28 Sep 2020
Ok thanks, I also discovered another way but it requires an input. It seems like yours won't require one.
a(1) = 0;
a(2) = 1;
a(3) = 2;
n= input('enter the number of terms desired: ');
for i = 4:n
a(i) = a(i-1) + a(i-2) + a(i-3);
end
Ameer Hamza
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)

Community Treasure Hunt

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

Start Hunting!