I am unable to get any Cn values(FS coefficients) and also the graph did not appear. Also error said that (the value assigned to variable 'R' might be unused. I quite lost why and how

1 view (last 30 days)
clc; clear ; close all;
%Define parameters
Xo=1; %amplitude
T=10; % Total range
To=20; %period
n=8; %8 harmonics
N=1001; %Number of points to consider
t=linspace(-(-To-T),(To-T),N); %Time axis
x=zeros(1,N); x(t>=-T/2 & t<=T/2) = Xo; %original signal
R=0; % initialize approximated signal
k=-n:n; %Fourier coefficient number axis
f=zeros(1,2*n+1); %Fourier coefficient values
for c=0:n
for nh = -c:c
if nh~=0
Sinc = (sin(pi*nh*T/To)/((pi*nh*T/To)));
else
Sinc = 1;
end
Cn = (Xo*T/To)*Sinc ; %actual FS coefficient
f(k==nh) = Cn; %put the FS coefficient at respective places
R = R + Cn*exp(1j*nh*2*pi/To.*t);
end
R = real (R) ; %to get rid of imaginary factor
%plots
%for plotting the magnitude spectra and plot the FS coefficients
subplot 121; stem (k,f); grid on ;
xlabel('Fourier coefficient index') ; ylabel('magnitude');
title('Fourier coefficients');
R=0; %reset approxmation to calc a new one
%for plot gibbs phenomenon
subplot 122; plot(t,x,t,R); grid on;
xlabel('Time(t)'); ylabel('Amplitude');
title (['Approximation for n=8', nums2str(c)]);
end

Answers (1)

Cris LaPierre
Cris LaPierre on 1 Aug 2020
The only error I get with your code is in the last line: nums2str
Once I replaced it with num2str, it ran without error and generated a couple plots. I can't tell you if the values generated are correct or not, though.

Community Treasure Hunt

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

Start Hunting!