How can I generate the sequence f(n+1) = f(n) + sin(n*pi/2)*(-3) + (cos(n*pi/2)).^2?

I'd like to generate the sequence
f(n+1) = f(n) + sin(n*pi/2)*(-3) + (cos(n*pi/2)).^2
for a set number of terms, say N.
I have been tearing my hair out trying to figure it out (first time using MATLAB) and have gotten nowhere.
I've tried for loops, and I would like to know if this is how it's done. If not, could someone show me how to? I've also tried using start:step:end with sin(n*pi/2)*(-3) + (cos(n*pi/2)).^2 as the step, but obviously this doesn't work.
I'd like the terms of the sequence to be a row in a matrix eventually, as well.
Thanks.

1 Comment

BTW, f(0) = 3 and f(N) = 60. Is there some way MATLAB can calculate the index of the last term using the formula?

Sign in to comment.

Answers (1)

James - you say that you have tried using start:step:end with sin(n*pi/2)*(-3) + (cos(n*pi/2)).^2. What was the code that you were using to do this?
A for loop would be used for this recurrence relation equation. Just initialize your array f to the appropriate size given N remembering that MATLAB array indexing is one based (not zero based) so the first element would be
f(1) = 0;
then use your for loop to update the kth element of f given the value found in the previous iteration
for k=1:N+1
f(k) = ...;
end
EDIT
As indicated by Image Analyst, the loop should be set as
for k=1:N-1
f(k+1) = ...;
end
or
for k=2:N
f(k) = ...;
end

2 Comments

To get N total terms in the function/array, wouldn't you start at 1 and end at N-1?
for n = 1 : N - 1
f(n+1) = f(n) + sin(n*pi/2)*(-3) + (cos(n*pi/2)).^2
So when n = (N-1), then n+1 will equal N and that will be the last (Nth) term and you'll have N total terms.
You're correct - if James wants N terms then he would iterate as you have described above. I will edit my answer.

Sign in to comment.

Asked:

on 7 Mar 2015

Edited:

on 7 Mar 2015

Community Treasure Hunt

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

Start Hunting!