Error using Plot for Fourier Series

조회 수: 4 (최근 30일)
Anthony Koning
Anthony Koning 2022년 2월 20일
편집: Torsten 2022년 2월 20일
Hi, I believe I'm close to getting the summation of a Fourier Series plot for different values of N without using add-ons. My code is as follows:
t = [0:0.01:4]; % time grid
n = [1:1:10]; % range of n
x = 0.5 + 2./pi.*sum((-1).^(n-1).*cos(((2.*n)-1)*pi/2.*x'))./(2.*n-1); % summation
% plot
figure;
plot(t, x);
xlabel('t');
ylabel('x');
however, I keep getting an error stating that vectors lengths don't match, but don't see how. If someone could explain, I'd appreciate it.
For context, this is what the series is supposed to look like written out:

채택된 답변

Star Strider
Star Strider 2022년 2월 20일
I beleive there is a typographical error in the ‘x’ assignment. I changed the ‘x’ to ‘t’ on the RHS and it works. Also, the summation needs to include the entire expression, so I changed the location of the closing parentheses in the sum call.
t = [0:0.01:4]; % time grid
n = [1:1:10]; % range of n
n = n(:); % Force Column Vector
x = 0.5 + 2./pi.*sum((-1).^(n-1).*cos(((2.*n)-1)*pi/2.*t)./(2.*n-1)); % summation
% plot
figure;
plot(t, x);
xlabel('t');
ylabel('x');
Other that those (and forcing ‘n’ to be a column vector), the code is unchanged.
.

추가 답변 (2개)

Paul
Paul 2022년 2월 20일
Something doesn't look right with x on the left and right hand sides of the equation. Maybe the x on the right hand side should be t, so that the equation reconstructs x(t)? Or, since the closed form equation uses x as the indpendent variable on the rhs, in the code set x = 0:.01:4 and use a different variable on the lhs, like z?
Also, it looks like the argument to the sum() is constructing a matrix with n varying across the columns and x varying down the rows. The sum should be over n, but the actual sum() command defaults to summing down each column. Use the second argument to sum() to tell it to sum across the columns
sum(...., 2)

Torsten
Torsten 2022년 2월 20일
편집: Torsten 2022년 2월 20일
x = 0:0.01:4;
N = 10;
n = 1:N;
for i=1:numel(x)
f(i) = 0.5 + 2/pi*sum((-1).^(n-1).*cos((2*n-1)*pi*x(i)/2)./(2*n-1));
end
plot(x,f)

카테고리

Help CenterFile Exchange에서 Special Functions에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by