If I want to add the previous 3 terms in a sequence how would I do it?
1 次查看(过去 30 天)
显示 更早的评论
Say for example the sequence results in 0, 1, 2, 3, 6, 11, ...
0 个评论
采纳的回答
Ameer Hamza
2020-9-28
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 个评论
Ameer Hamza
2020-9-28
编辑:Ameer Hamza
2020-9-28
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
2020-9-28
But then the preallocation will be gone, which is usually a recommended practice.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!