Wrong answer to straightforward problem:

2 ビュー (過去 30 日間)
DJ V
DJ V 2016 年 12 月 6 日
回答済み: DJ V 2016 年 12 月 6 日
* 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.

採用された回答

Steven Lord
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.]

その他の回答 (1 件)

DJ V
DJ V 2016 年 12 月 6 日
Thanks a lot, that was the problem.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by