Hi All. After get some hints from Jon and other references. I adjusted my code like below and it seems works better now.
However, I still have some confusions:
- Why should I reduce sampling time step ts and signal frequency change vel beta, expand max time tMax to get better results (It seems the smaller ts and beta, bigger tMax could lead better result)?
- How could I get bode plot for an unstable system through experiment method which means I didn't know transfer function of the system at first?
Maybe any one could give me some hints.
Code:
%% pre-operation
clear
close all
clc
%% define transfer function
num = [1 1];
den = [1 1 10];
gs = tf(num,den);
if ~isstable(gs)
disp('Err: system unstable!')
return
end
%% generate excitation signal(chirp type)
ts = 0.00025; % sampling time step
tMax = 5; % max time
t = 0:ts:(tMax-ts); % time sequence
a = 1; % signal amplitude
beta = 50; % signal change vel
fIni = 0; % initial freq
fEnd = beta*t(end); % target freq
in = a*cos(2*pi*(beta*t+fIni).*t); % excitation signal(chirp type)
freq = beta*t; % freq sequence
%% plot excitation signal
figure
hold on
plot(t,in)
hold off
legend
grid on
box on
xlabel('time/s')
ylabel('counts')
title('Excitation signal in time domain')
%% get output data
out = lsim(gs,in,t)';
%% plot time domain input and output signal
figure
hold on
plot(t,in)
plot(t,out)
hold off
legend
grid on
box on
xlabel('time/s')
ylabel('counts')
title('Input and output in time domain from simulink')
%% bode diagram data calculation
input = in;
output = out;
time = t;
Fs = 1/ts; % sampling frequency
Fn = Fs/2; % nyquist frequency
L = numel(time);
FTinp = fft(input)/L;
FTout = fft(output)/L;
TF = FTout ./ FTinp; % transfer function
Fv = linspace(0, 1, fix(L/2)+1)*Fn; % frequency vector
Iv = 1:numel(Fv); % index vector
%% plot bode from tf and measured data
figure
hold on
bodeOp = bodeoptions;
bodeOp.FreqUnits = 'Hz';
bodemag(gs,bodeOp)
semilogx(Fv, 20*log10(abs(TF(Iv))),'-.','linewidth',2)
legend('bode plot from tf','bode plot from measured data')
grid on
xlim([0.1,1000])
Result:
Reference: