I have created the following simulink model with two blocks one with direct addition and the other block with a unit delay. The simulink configuration parameters are fixed step solver with 0.2 fixed step size. Now my doubt is for the blocks without unit delay the output is available at 0th simulation time which is 2 but in case of unit delay the output is 0 at 0th simulation time. Why? simulink model sorry but i am unable to attch the model.
You can think of your Simulink diagrams as of the discrete linear dynamical systems with inputs and outputs. Using the transfer function approach, such systems can be represented via
(1) Y(z)=G(z)X(z),
where Y(z) is the out of the system, X(z) is the input and G(z) is the transfer function (note: I omitted the initial conditions at this stage for the simplicity of explanation). Each individual block of the system can also be treated as the system of the form (1).
Consider your first diagram. The constant block expressed in the input output form (1) is
(2) Y1(z) = G1(z)X(z),
with: G1(z) = 1, i.e.
(3) Y1(z) = X(z).
Each Simulink 'unit delay' block can be treated as a system of the form (1) with the transfer function of the form Gu(z) = z^(-1). Denote the transfer function associated with the 'unit delay' block in the middle of the diagram as G2(z) and the one at the bottom of the diagram as G3(z). In this case, we have G3(z) = G2(z) = Gu(z) = z^(-1). Note that the input to the system associated with G2 is the output of the system (3) and the input to the system associated with G3 is the output of the system associated with G2. Taking into account the considerations above, the systems that correspond to the unit delay blocks associated with G1 and G2 are given by (4) and (5), respectively.
(4) Y2(z) = G2(z)*Y1(z) = z^(-1)*Y1(z) = z^(-1)*G1(z)*X(z) = z^(-1)*X(z)
(5) Y3(z) = G3(z)Y2(z) = z^(-1)*z^(-1)*X(z) = z^(-2)*X(z)
Assuming that the output of the system associated with the entire model is denoted Y(z) and corresponds to the output of the summation block, the transfer function of the entire system can be expressed as
(6) Y(z) = Y1(z) + Y2(z) + Y3(z)
To summarise:
(7a) Y1(z) = X(z)
(7b) Y2(z) = z^(-1)*Y1(z)
(7c) Y3(z) = z^(-1)*Y2(z)
(7d) Y(z) = Y1(z) + Y2(z) + Y3(z)
The system above corresponds to a difference equation of the form
(8a) y1(k) = x(k)
(8b) y2(k) = y1(k-1)
(8c) y2(k) = y2(k-1)
(8d) y(k) = y1(k) + y2(k) + y3(k)
To see this, you can apply Z-transform to the equation (8) above. You can assume that in Simulink, the simulation always starts at k=0 (to obtain the 'physical time' that associated with the output you would need to use t(k) = k*T, where T is the sampling time set in the solver properties). Thus, you would need to provide the values of y1(k) and y2(k) for k=-1 to be able to solve the system for all k>=0.
All Simulink blocks that represent transfer functions (be it discrete or continuous) allow the assignment of initial conditions. For discrete systems, the initial conditions are assumed to be valid for all k<=0 (or t<=0 if you consider physical time). The default initial condition for the blocks that represent transfer functions is 0. Thus, when you simulate the system (8), Simulink assumes that y1(-1)=0, y2(-1)=0. The constant block assigns x(k) = 1 for all k>=0.
Given what is stated above, let us calculate the values of the system (8) at time steps k=0,1,2.
At k=0:
y1(0) = x(0) = 1, y2(0) = y1(-1) = 0, y3(0) = y2(-1) = 0, y(0) = 1
At k=1:
y2(1) = x(1) = 1, y2(1) = y1(0) = 1, y3(1) = y2(0) = 0, y(0) = 2
At k=2:
y2(2) = x(2) = 1, y2(2) = y1(1) = 1, y3(2) = y2(1) = 1, y(0) = 3
Related
I've implement a moving maximum filter in matlab and now I have to determine if it's LTI or not. I've already prove it's linear but I can't prove if it's time ivnariant. To prove this I have to give as an input a signal x[n] and get the output X[n]. After that I'm giving the same signal but this time it have to delay it that is x[n-a] and the output must be X[n-a] the same as the X[n] but delayed. My problem is that I don't know what input to give. Also, the moving maximum is a LTI system or not?
Thanks in advance.
Max-Filter Using For-Loop and Testing System for Linear and Time-Invariance
Filter Construction:
To filter an array/matrix/signal a for-loop can be applied. Within this for-loop, portions of the signal that overlaps the window must be stored in this case called Window_Sample. To apply the maximum filter the max() of the Window_Sample must be taken upon each iteration of the loop. Upon each iteration of the loop the window moves. Here I push all the code that calculates the maximum filtered signal into a function called Max_Filter().
Time-Invariant or Not-Time Invariant:
With proper padding, I think the maximum filter is time-invariant/shift-invariant. Concatenating zeros to the start and ends of the signal is a good way to combat this. The amount of padding I used on each end is the size of the window, the requirement would be half the window but there's no harm in having a little bit of buffer. Unfortunately, without proper padding, this may appear to break down in MATLAB since the max filter will be introduced to points early. In this case without padding the ramp the max filter will take the 5th point as the max right away. Here you can apply a scaling factor to test if the system is linear. You'll see that the system is not linear since the output is not a scaled version of the input.
clf;
%**********************************************************%
%ADJUSTABLE PARAMETERS%
%**********************************************************%
Window_Size = 3; %Window size for filter%
Delay_Size = 5; %Delay for the second test signal%
Scaling_Factor = 1; %Scaling factor for the second test signal%
n = (0:10);
%Ramp function with padding%
Signal = n; %Function for test signal%
%**********************************************************%
Signal = [zeros(1,Window_Size) Signal zeros(1,Window_Size)];
Filtered_Result_1 = Max_Filter(Signal,Window_Size);
%Ramp function with additional delay%
Delayed_Signal = Scaling_Factor.*[zeros(1,Delay_Size) Signal];
Filtered_Result_2 = Max_Filter(Delayed_Signal,Window_Size);
plot(Filtered_Result_1);
hold on
plot(Filtered_Result_2);
xlabel("Samples [n]"); ylabel("Amplitude");
title("Moving Maximum Filtering Signal");
legend("Original Signal","Delayed Signal");
xticks([0: 1: length(Filtered_Result_2)]);
xlim([0 length(Filtered_Result_2)]);
grid;
function [Filtered_Signal] = Max_Filter(Signal,Filter_Size)
%Initilizing an array to store filtered signal%
Filtered_Signal = zeros(1,length(Signal));
%Filtering array using for-loop and acccesing chunks%
for Sample_Index = 1: length(Signal)
Start_Of_Window = Sample_Index - floor(Filter_Size/2);
End_Of_Window = Sample_Index + floor(Filter_Size/2);
if Start_Of_Window < 1
Start_Of_Window = 1;
end
if End_Of_Window > length(Signal)
End_Of_Window = length(Signal);
end
Window_Sample = Signal(Start_Of_Window:End_Of_Window);
Filtered_Signal(1,Sample_Index) = max(Window_Sample);
end
end
Alternatively Using Built-In Functions:
To test the results of the created filter it is a good idea to compare this to the output results of MATLAB's built-in function movmax(). Here the results appear to be the same as the for-loop implementation.
clf;
Window_Size = 3;
n = (0:10);
%Ramp function with padding%
Signal = n;
Signal = [zeros(1,Window_Size) Signal zeros(1,Window_Size)];
Filtered_Result_1 = movmax(Signal,Window_Size);
%Ramp function with additional delay%
Delay_Size = 5;
Delayed_Signal = [zeros(1,Delay_Size) Signal];
Filtered_Result_2 = movmax(Delayed_Signal,Window_Size);
plot(Filtered_Result_1);
hold on
plot(Filtered_Result_2);
xlabel("Samples [n]"); ylabel("Amplitude");
title("Moving Maximum Filtering Signal");
legend("Original Signal","Delayed Signal");
xticks([0: 1: length(Filtered_Result_2)]);
xlim([0 length(Filtered_Result_2)]);
grid;
Ran using MATLAB R2019b
I have a discrete transfer function whose numerator and denominator are coming from an input port. At every sample time these numerator and denominator vectors change.
E.g.
# t == 0
den == [1 0 -1]
# t == 1
den == [1 0 0 -1]
What do I have to do in order for the transfer function to work with this?
I have tried:
Having a variable length signal.
SIMULINK did not like this and refused to run, complaining that the discrete transfer function block could not handle variable sized input.
Padding the vector with many leading zeros
This led to periodic spikes in the signal. Additionally, Simulink does not let you do this if you enter the values by hand, rather than as an input, so I don't think this is the way to do it either.
Any help is much appreciated.
This is solved trivially with a single Simulink S-Function file sfuntvf.m, like this.
In there, a custom fixed vector state with y and us history is saved, and the time varying part is simply applied over the time history (depicted in cyan and yellow); here a FIR Filter with a random order (depicted in magenta).
Other build-in implementations shall consider the sucessive initial conditions between calls, and require the verification of the initial condition structure. The shown implementation is the easiest to deploy and understand.
The A and B vectors can be modified accordingly.
function [sys,x0,str,ts] = sfuntvf(t,x,u,flag)
N=20;
n=randi(N-2)+1;
A=[1;zeros(N-1,1)];
B=[1/n*ones(n,1);zeros(N-n,1)];
switch flag,
case 0, [sys,x0,str,ts] = mdlInitializeSizes(N);
case 2, sys = mdlUpdate(t,x,u,N,A,B);
case 3, sys = mdlOutputs(t,x,u,N,n);
case 9, sys = [];
otherwise DAStudio.error('Simulink:blocks:unhandledFlag',num2str(flag));
end
function [sys,x0,str,ts] = mdlInitializeSizes(N)
sizes = simsizes;
sizes.NumContStates = 0;
sizes.NumDiscStates = 2*N;
sizes.NumOutputs = 2;
sizes.NumInputs = 1;
sizes.DirFeedthrough = 0;
sizes.NumSampleTimes = 1;
sys = simsizes(sizes);
x0 = zeros(2*N,1);
str = [];
ts = [1 0];
function sys = mdlUpdate(t,x,u,N,A,B)
un=x(1:N,1);
yn=x(N+1:2*N,1);
y=-A(2:end)'*yn(2:end)+B'*un;
sys = [u;un(1:end-1);y;yn(1:end-1)];
function sys = mdlOutputs(t,x,u,N,n)
sys = [x(N+1);n];
Hi everyone i'm new to matlab and i have some problem with the ga function.
I must find the best integer values of input and output delays for a net applied to a time series problem using genetic algorithm.
I write a fitting function that using 2 variables as input and output delays create the net and return the performance value.
I want 2 delays between 1 and 10 so i use the ga function like this
[x,fval,exitflag,output,population,scores] = ga(#rendimentoRete, 2, [], [], [], [], [1 1], [10 10], [], [1 2])
And i have this error "Output argument "out" (and maybe others) not assigned during call to"D:\Documents\MATLAB\rendimentoRete.m>rendimentoRete"."
This is my fitting function
(if someone prefer this is the same function on pastebin with Syntax Highlighting http://pastebin.com/5iwzwhi0)
function out = rendimentoRete(iDelay, oDelay)
if nargin < 2
return;
end
%%carico le variabili dal workspace in modo che la funzione di fitness
%%conservi come varibili di ingresso solo i delay
load baseSet.mat;
inputSeries = tonndata(first_period,false,false);
targetSeries = tonndata(first_usd_ise,false,false);
% Create a Nonlinear Autoregressive Network with External Input
inputDelays = 1:iDelay;
feedbackDelays = 1:oDelay;
hiddenLayerSize = 8;
net = narxnet(inputDelays,feedbackDelays,hiddenLayerSize);
% Prepare the Data for Training and Simulation
% The function PREPARETS prepares timeseries data for a particular network,
% shifting time by the minimum amount to fill input states and layer states.
% Using PREPARETS allows you to keep your original time series data unchanged, while
% easily customizing it for networks with differing numbers of delays, with
% open loop or closed loop feedback modes.
[inputs,inputStates,layerStates,targets] = preparets(net,inputSeries,{},targetSeries);
% Setup Division of Data for Training, Validation, Testing
net.divideParam.trainRatio = 70/100;
net.divideParam.valRatio = 15/100;
net.divideParam.testRatio = 15/100;
% Train the Network
for j=1:10
[net,tr] = train(net,inputs,targets,inputStates,layerStates);
end
% Test the Network
outputs = net(inputs,inputStates,layerStates);
errors = gsubtract(targets,outputs);
performance = perform(net,targets,outputs); %%alt -> MSE
%prova1
out = performance;
%{
%prova2
%converto l'output a un vettore e approssimo i risultati ai valori 1 e -1
%convert outputs cell to array
outputs_array = cell2mat(outputs);
%convertiamo outputs_array
for k=1:(268-outputDelay)
if outputs_array(k)>0
outputs_array(k)=1;
else
outputs_array(k)=-1;
end
end
out = performance + calcoloMape(outputDelay, first_usd_ise, outputs_array) + calcoloPgcp(outputDelay, first_usd_ise, outputs_array);
%}
end
with the load of baseSet.mat i'm loading first_period and first_usd_ise because they are always the same.
I can't figure out what to do because when i use the function stand alone gives me good result.
Someone can explain me where i mistake.
According to the documentation for MATLAB's ga, the signature of the fitness function is described as
...should accept a row vector of length nvars and return a scalar value.
That means that your function signature has to change from one with two input variables like
function out = rendimentoRete(iDelay, oDelay)
to a signature with just one input variable like
function out = rendimentoRete(inputVars)
where inputVars is a vector whereby you can obtain the two variables as
iDelay = inputVars(1);
oDelay = inputVars(2);
Modify your function signature and first two lines to the above (you can remove the margin check), try it out, and see what happens!
I have the following Markov chain:
This chain shows the states of the Spaceship, which is in the asteroid belt: S1 - is serviceable, S2 - is broken. 0.12 - the probability of destroying the Spaceship by a collision with an asteroid. 0.88 - the probability of that a collision will not be critical. Need to find the probability of a serviceable condition of the ship after the third collision.
Analytical solution showed the response - 0.681. But it is necessary to solve this problem by simulation method using any modeling tool (MATLAB Simulink, AnyLogic, Scilab, etc.).
Do you know what components should be used to simulate this process in Simulink or any other simulation environment? Any examples or links.
First, we know the three step probability transition matrix contains the answer (0.6815).
% MATLAB R2019a
P = [0.88 0.12;
0 1];
P3 = P*P*P
P(1,1) % 0.6815
Approach 1: Requires Econometrics Toolbox
This approach uses the dtmc() and simulate() functions.
First, create the Discrete Time Markov Chain (DTMC) with the probability transition matrix, P, and using dtmc().
mc = dtmc(P); % Create the DTMC
numSteps = 3; % Number of collisions
You can get one sample path easily using simulate(). Pay attention to how you specify the initial conditions.
% One Sample Path
rng(8675309) % for reproducibility
X = simulate(mc,numSteps,'X0',[1 0])
% Multiple Sample Paths
numSamplePaths = 3;
X = simulate(mc,numSteps,'X0',[numSamplePaths 0]) % returns a 4 x 3 matrix
The first row is the X0 row for the starting state (initial condition) of the DTMC. The second row is the state after 1 transition (X1). Thus, the fourth row is the state after 3 transitions (collisions).
% 50000 Sample Paths
rng(8675309) % for reproducibility
k = 50000;
X = simulate(mc,numSteps,'X0',[k 0]); % returns a 4 x 50000 matrix
prob_survive_3collisions = sum(X(end,:)==1)/k % 0.6800
We can bootstrap a 95% Confidence Interval on the mean probability to survive 3 collisions to get 0.6814 ± 0.00069221, or rather, [0.6807 0.6821], which contains the result.
numTrials = 40;
ProbSurvive_3collisions = zeros(numTrials,1);
for trial = 1:numTrials
Xtrial = simulate(mc,numSteps,'X0',[k 0]);
ProbSurvive_3collisions(trial) = sum(Xtrial(end,:)==1)/k;
end
% Mean +/- Halfwidth
alpha = 0.05;
mean_prob_survive_3collisions = mean(ProbSurvive_3collisions)
hw = tinv(1-(0.5*alpha), numTrials-1)*(std(ProbSurvive_3collisions)/sqrt(numTrials))
ci95 = [mean_prob_survive_3collisions-hw mean_prob_survive_3collisions+hw]
maxNumCollisions = 10;
numSamplePaths = 50000;
ProbSurvive = zeros(maxNumCollisions,1);
for numCollisions = 1:maxNumCollisions
Xc = simulate(mc,numCollisions,'X0',[numSamplePaths 0]);
ProbSurvive(numCollisions) = sum(Xc(end,:)==1)/numSamplePaths;
end
For a more complex system you'll want to use Stateflow or SimEvents, but for this simple example all you need is a single Unit Delay block (output = 0 => S1, output = 1 => S2), with a Switch block, a Random block, and some comparison blocks to construct the logic determining the next value of the state.
Presumably you must execute the simulation a (very) large number of times and average the results to get a statistically significant output.
You'll need to change the "seed" of the random generator each time you run the simulation.
This can be done by setting the seed to be "now" (or something similar to that).
Alternatively you could quite easily vectorize the model so that you only need to execute it once.
If you want to simulate this, it is fairly easy in matlab:
servicable = 1;
t = 0;
while servicable =1
t = t+1;
servicable = rand()<=0.88
end
Now t represents the amount of steps before the ship is broken.
Wrap this in a for loop and you can do as many simulations as you like.
Note that this can actually give you the distribution, if you want to know it after 3 times, simply add && t<3 to the while condition.
The final goal I am trying to achieve is the generation of a ten minutes time series: to achieve this I have to perform an FFT operation, and it's the point I have been stumbling upon.
Generally the aimed time series will be assigned as the sum of two terms: a steady component U(t) and a fluctuating component u'(t). That is
u(t) = U(t) + u'(t);
So generally, my code follows this procedure:
1) Given data
time = 600 [s];
Nfft = 4096;
L = 340.2 [m];
U = 10 [m/s];
df = 1/600 = 0.00167 Hz;
fn = Nfft/(2*time) = 3.4133 Hz;
This means that my frequency array should be laid out as follows:
f = (-fn+df):df:fn;
But, instead of using the whole f array, I am only making use of the positive half:
fpos = df:fn = 0.00167:3.4133 Hz;
2) Spectrum Definition
I define a certain spectrum shape, applying the following relationship
Su = (6*L*U)./((1 + 6.*fpos.*(L/U)).^(5/3));
3) Random phase generation
I, then, have to generate a set of complex samples with a determined distribution: in my case, the random phase will approach a standard Gaussian distribution (mu = 0, sigma = 1).
In MATLAB I call
nn = complex(normrnd(0,1,Nfft/2),normrnd(0,1,Nfft/2));
4) Apply random phase
To apply the random phase, I just do this
Hu = Su*nn;
At this point start my pains!
So far, I only generated Nfft/2 = 2048 complex samples accounting for the fpos content. Therefore, the content accounting for the negative half of f is still missing. To overcome this issue, I was thinking to merge the real and imaginary part of Hu, in order to get a signal Huu with Nfft = 4096 samples and with all real values.
But, by using this merging process, the 0-th frequency order would not be represented, since the imaginary part of Hu is defined for fpos.
Thus, how to account for the 0-th order by keeping a procedure as the one I have been proposing so far?