# Error using Plot for Fourier Series

2 vues (au cours des 30 derniers jours)
Anthony Koning le 20 Fév 2022
Modifié(e) : Torsten le 20 Fév 2022
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:
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Star Strider le 20 Fév 2022
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.
.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Plus de réponses (2)

Paul le 20 Fév 2022
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)
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

Torsten le 20 Fév 2022
Modifié(e) : Torsten le 20 Fév 2022
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)
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Signal Generation and Preprocessing dans Help Center et File Exchange

R2021a

### Community Treasure Hunt

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

Start Hunting!

Translated by