summing to create a vector
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2016-6-3
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 个评论
Walter Roberson
2016-6-5
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.
更多回答(1 个)
Azzi Abdelmalek
2016-6-3
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!