To simulate the SIMULINK model on MATLAB

I have been trying yo simulate the current SIMULINK block to a MATLAB program.
I got this result.
I have tried to simulate the same wave using MATLAB but I got the below results. I can't understand why for the similar integrators the simulated wave seems different. Is there any better way to to get the same simulink result on MATLAB??
clc;
clear all;
close all;
%Matlab program for a resonator
w=3; %Frequency in radians
Gain=-1; %Gain of the resonator
K1=1; %Gain of integrator 1
K2=1; %Gain of integrator 2
T=0.01; %Sample Time
%Define input and output of the resonator
n=0:T:20;
y1=zeros(1,length(n));
y2=zeros(1,length(n));
x1=zeros(1,length(n));
x2=zeros(1,length(n));
u1=zeros(1,length(n));
u2=zeros(1,length(n));
u1(1:length(n))=w*Gain;
x1(1)=1; x2(1)=0;
%y1(1)=1; y2(1)=0;
for i=1:1:length(n)
%Backward Euler method (Integrator 1)
for n1=1:1:length(n)
y1(n1)=x1(n1)+K1*T*u1(n1);
x1(n1+1)=y1(n1);
end
u2(1:length(n))=y1*w; %Input to Integrator 2
%Forward Euler method (Integrator 2)
for n2=1:1:length(n)
y2(n2)=x2(n2);
x2(n2+1)=x2(n2)+K2*T*u2(n2);
end
u1(1:length(n))=Gain*y2; %Input to Integrator 1
end
plot(n,y1,'ro',n,y2,'bo');
xlabel('Time(seconds)');
ylabel('Amplitude');
title('Sine and Cosine of the resonator');
legend('Integrator 1 (Backward Euler)','Integrator 2 (Forward Euler)');
grid on;

 Accepted Answer

The following loop seems to do it:
for i=1:1:length(n)
%Backward Euler method (Integrator 1)
for n1=1:1:length(n)
y1(n1)=x1(n1)+K1*T*u1(n1)*w;
x1(n1+1)=y1(n1);
end
u2(1:length(n))= y1; %Input to Integrator 2
%Forward Euler method (Integrator 2)
for n2=1:1:length(n)
y2(n2)=x2(n2);
x2(n2+1)=x2(n2)+K2*T*u2(n2)*w;
end
u1(1:length(n))=Gain*y2; %Input to Integrator 1
end
plot(n,y1,'r',n,y2,'b');

More Answers (0)

Categories

Find more on Simulink in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!