Error using Plot for Fourier Series

2 次查看(过去 30 天)
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 中查找有关 Programming 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by