summing to create a vector
2 views (last 30 days)
Show older comments
OLUBUKOLA ogunsola
on 3 Jun 2016
Commented: Walter Roberson
on 5 Jun 2016
I'm trying to write a function that calculates sum of ((-1)^k *sin((2k+1)t))/((2k+1)^2 ( for k=0 to n) t varies from 0 to 4*pi with 1001 values its supposed to return a vector with size n this is the code i wrote
function [summ ]= triangle_wave (n)
for k=1:n;
for t= linspace(0,4*pi,1001);
summ=sum((-1)^k*sin((2*k+1)*t))/((2*k+1)^2);
end
end
end
it keeps outputting the last calculate sum instead of adding each sum to the vector . what can i add to this code to achieve that ?
0 Comments
Accepted Answer
Walter Roberson
on 3 Jun 2016
function [summ ]= triangle_wave (n)
t = linspace(0,4*pi,1001);
summ = zeros(n+1, length(t));
for k = 1 : n;
summ(k+1,:) = summ(k,:) + (-1).^k .* sin((2*k+1) .* t)) ./ ((2*k+1).^2);
end
summ = summ(2:end,:);
end
2 Comments
Walter Roberson
on 5 Jun 2016
Instead of looping over the values of t, I use t as a vector, operating on all of the elements at once. Each iteration through I create an entire vector of values, the application of the formula with one particular k to the entire set of t values. Normally I would just add all of those together over all of the k, but you wanted to have all of the intermediate results for all of the different k, so it is necessary to store all of the results along the way.
The result for k = 1 is stored in row 2, the result for k = 2 is stored in row 3, and so on, until at the end one more row than n has been produced. You then omit the first row and take the rest as your answer.
The reason you do it this way is to make the code easier because each step involves adding to what the step before produced while still keeping what was produced in the previous step. That's easy to think of, but you have the practical difficulty of handling the very first output. You could code like
if k == 1
summ(k,:) = (-1).^k .* sin((2*k+1) .* t)) ./ ((2*k+1).^2);
else
summ(k,:) = summ(k-1,:) + (-1).^k .* sin((2*k+1) .* t)) ./ ((2*k+1).^2);
end
to avoid having to use the extra row, but you can see that you had to use special handling for the first row because for the first row there is no "previous" to add on to. The code is more compact if you do it the way I did, initialize a row with 0 to be there as the "previous" row.
More Answers (1)
Azzi Abdelmalek
on 3 Jun 2016
n=20
t= linspace(0,4*pi,1001);
for k=1:n
s(k)=sum((-1)^k *sin((2*k+1)*t)/((2*k+1)^2)) ;
end
s
2 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!