Wrong answer to straightforward problem:
1 次查看(过去 30 天)
显示 更早的评论
* Write a function called triangle_wave that computes the sum
for each of 1001 values of t uniformly spaced from 0 to 4π inclusive. The input argument is a scalar non-negative integer n, and the output argument is a row vector of 1001 such sums—one sum for each value of t. You can test your function by calling it with n == 20 or greater and plotting the result and you will see why the function is called “triangle_wave”.
My code is:
function [ out ] = triangle_wave( n )
%TRIANGLE_WAVE Summary of this function goes here
% Detailed explanation goes here
t = 4*pi/1000;
tvector = 0:t:4*pi;
length(tvector)
out = 0;
for count = 1:n+1
A= -1^(count-1);
B = sin((2*(count-1)+1)*tvector);
C = (2*(count-1)+1)^2;
triangle = A*B/C;
out = out + triangle;
end
end
This seems like it should be fairly straightforward.
0 个评论
采纳的回答
Steven Lord
2016-12-6
One problem is in this line.
A= -1^(count-1);
The power operator ^ is higher in operator precedence than the unary minus operator - so this is the equivalent of:
A= -(1^(count-1));
Wrap -1 in parentheses so you're raising minus 1 to a power rather than raising 1 to a power then negating it.
A= (-1)^(count-1);
You'll notice that this looks much more like the formula in your image. You should change the limit in your for loop, though, from 1:n+1 into 0:n to match the summation. [If you were storing each term individually in a vector or matrix you'd need to add 1 to the index into which to store the term, to account for the 1-based indexing of MATLAB, but you're not storing the terms just the sum of the terms.]
0 个评论
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!