Category: Matlab
Category Archives: Matlab
Can we generate C++ code from Simulink models from bash or PowerShell command line?
Can we generate C++ code from Simulink models from bash or PowerShell?
I am a beginner with Matlab and Simulink, I manage the build system for my company, we are trying to integrate a build step that will look at all the Simulink models and generates code for them. In order to achieve that, we need an interface to Simulink Coder from the command line and not inside Matlab or it’s add on applications.
Is this interface exposed ? and would this be a possibility ?Can we generate C++ code from Simulink models from bash or PowerShell?
I am a beginner with Matlab and Simulink, I manage the build system for my company, we are trying to integrate a build step that will look at all the Simulink models and generates code for them. In order to achieve that, we need an interface to Simulink Coder from the command line and not inside Matlab or it’s add on applications.
Is this interface exposed ? and would this be a possibility ? Can we generate C++ code from Simulink models from bash or PowerShell?
I am a beginner with Matlab and Simulink, I manage the build system for my company, we are trying to integrate a build step that will look at all the Simulink models and generates code for them. In order to achieve that, we need an interface to Simulink Coder from the command line and not inside Matlab or it’s add on applications.
Is this interface exposed ? and would this be a possibility ? simulink, matlab coder, code generation MATLAB Answers — New Questions
How to set eps^n =0 for all n>= 10 where eps is a symbolic variable.
Here is some Reduce code for an perturbation calculation:
1 factor eps;
2 x:=-1;
3 let eps^10=>0;
4 for iter:=1:2 do begin
5 write res:=x^2+x-eps;
6 write x:=x+a*res;
7 end;
and corresponding Mathematica code:
1 Clear[x,res,eps]
2 eps^n_ ^:=0 /; n>6;
3 x=-1;
4 While[res=!=0,
5 res=x^2+x-eps // Simplify;
6 x=Expand[x+res];
7 Print[x]
8 ];
I would like to know how to do line 3 in the Reduce code that sets all powers of eps^10 or greater equal to zero. The Mathematica code on line 2 does the same. I thought I could get subsex to do this but I can not figure out how to make say eps^12 =0 if eps^10=0, ie. obey the algebraic rules for powers like reduce does: eps^12 = eps^10 eps^2 = 0 since we let eps^10=0. I think maple’s function algsubs might be able to do this.Here is some Reduce code for an perturbation calculation:
1 factor eps;
2 x:=-1;
3 let eps^10=>0;
4 for iter:=1:2 do begin
5 write res:=x^2+x-eps;
6 write x:=x+a*res;
7 end;
and corresponding Mathematica code:
1 Clear[x,res,eps]
2 eps^n_ ^:=0 /; n>6;
3 x=-1;
4 While[res=!=0,
5 res=x^2+x-eps // Simplify;
6 x=Expand[x+res];
7 Print[x]
8 ];
I would like to know how to do line 3 in the Reduce code that sets all powers of eps^10 or greater equal to zero. The Mathematica code on line 2 does the same. I thought I could get subsex to do this but I can not figure out how to make say eps^12 =0 if eps^10=0, ie. obey the algebraic rules for powers like reduce does: eps^12 = eps^10 eps^2 = 0 since we let eps^10=0. I think maple’s function algsubs might be able to do this. Here is some Reduce code for an perturbation calculation:
1 factor eps;
2 x:=-1;
3 let eps^10=>0;
4 for iter:=1:2 do begin
5 write res:=x^2+x-eps;
6 write x:=x+a*res;
7 end;
and corresponding Mathematica code:
1 Clear[x,res,eps]
2 eps^n_ ^:=0 /; n>6;
3 x=-1;
4 While[res=!=0,
5 res=x^2+x-eps // Simplify;
6 x=Expand[x+res];
7 Print[x]
8 ];
I would like to know how to do line 3 in the Reduce code that sets all powers of eps^10 or greater equal to zero. The Mathematica code on line 2 does the same. I thought I could get subsex to do this but I can not figure out how to make say eps^12 =0 if eps^10=0, ie. obey the algebraic rules for powers like reduce does: eps^12 = eps^10 eps^2 = 0 since we let eps^10=0. I think maple’s function algsubs might be able to do this. algsubs, subsex MATLAB Answers — New Questions
How to set eps^n =0 for all n>= 10 where eps is a symbolic variable.
Here is some Reduce code for an perturbation calculation:
1 factor eps;
2 x:=-1;
3 let eps^10=>0;
4 for iter:=1:2 do begin
5 write res:=x^2+x-eps;
6 write x:=x+a*res;
7 end;
and corresponding Mathematica code:
1 Clear[x,res,eps]
2 eps^n_ ^:=0 /; n>6;
3 x=-1;
4 While[res=!=0,
5 res=x^2+x-eps // Simplify;
6 x=Expand[x+res];
7 Print[x]
8 ];
I would like to know how to do line 3 in the Reduce code that sets all powers of eps^10 or greater equal to zero. The Mathematica code on line 2 does the same. I thought I could get subsex to do this but I can not figure out how to make say eps^12 =0 if eps^10=0, ie. obey the algebraic rules for powers like reduce does: eps^12 = eps^10 eps^2 = 0 since we let eps^10=0. I think maple’s function algsubs might be able to do this.Here is some Reduce code for an perturbation calculation:
1 factor eps;
2 x:=-1;
3 let eps^10=>0;
4 for iter:=1:2 do begin
5 write res:=x^2+x-eps;
6 write x:=x+a*res;
7 end;
and corresponding Mathematica code:
1 Clear[x,res,eps]
2 eps^n_ ^:=0 /; n>6;
3 x=-1;
4 While[res=!=0,
5 res=x^2+x-eps // Simplify;
6 x=Expand[x+res];
7 Print[x]
8 ];
I would like to know how to do line 3 in the Reduce code that sets all powers of eps^10 or greater equal to zero. The Mathematica code on line 2 does the same. I thought I could get subsex to do this but I can not figure out how to make say eps^12 =0 if eps^10=0, ie. obey the algebraic rules for powers like reduce does: eps^12 = eps^10 eps^2 = 0 since we let eps^10=0. I think maple’s function algsubs might be able to do this. Here is some Reduce code for an perturbation calculation:
1 factor eps;
2 x:=-1;
3 let eps^10=>0;
4 for iter:=1:2 do begin
5 write res:=x^2+x-eps;
6 write x:=x+a*res;
7 end;
and corresponding Mathematica code:
1 Clear[x,res,eps]
2 eps^n_ ^:=0 /; n>6;
3 x=-1;
4 While[res=!=0,
5 res=x^2+x-eps // Simplify;
6 x=Expand[x+res];
7 Print[x]
8 ];
I would like to know how to do line 3 in the Reduce code that sets all powers of eps^10 or greater equal to zero. The Mathematica code on line 2 does the same. I thought I could get subsex to do this but I can not figure out how to make say eps^12 =0 if eps^10=0, ie. obey the algebraic rules for powers like reduce does: eps^12 = eps^10 eps^2 = 0 since we let eps^10=0. I think maple’s function algsubs might be able to do this. algsubs, subsex MATLAB Answers — New Questions
unable to download Matlab trail
I need matlab trail version. but its not getting downloaded rather redirecting to the page again and again to below one .kindly help meI need matlab trail version. but its not getting downloaded rather redirecting to the page again and again to below one .kindly help me I need matlab trail version. but its not getting downloaded rather redirecting to the page again and again to below one .kindly help me get a trail loop MATLAB Answers — New Questions
unable to download Matlab trail
I need matlab trail version. but its not getting downloaded rather redirecting to the page again and again to below one .kindly help meI need matlab trail version. but its not getting downloaded rather redirecting to the page again and again to below one .kindly help me I need matlab trail version. but its not getting downloaded rather redirecting to the page again and again to below one .kindly help me get a trail loop MATLAB Answers — New Questions
Computer Login Name for license center
The article explaining how to find my computer login name is disabled. Apparently because it’s been 14 days or something. Can someone tell me how to either access the article or find the name?The article explaining how to find my computer login name is disabled. Apparently because it’s been 14 days or something. Can someone tell me how to either access the article or find the name? The article explaining how to find my computer login name is disabled. Apparently because it’s been 14 days or something. Can someone tell me how to either access the article or find the name? login name, license, installation MATLAB Answers — New Questions
Unable to generate code with shared exported files witout deleting .dmr file in _sharedutils folder
My physical system (parent model) consists of different smaller subsystems, that all run on separate ECUs, thus are referenced models for separate code generation. All of the subsystems share some buses, which are exported in the global .sldd file, and saved to a file sharedSimulinkTypes.h, which is generated under the _sharedutils folder. When a shared bus is changed, generating code will result in an error, stating:
The contents of the following objects do not match those in the current slprj directory:
Content
‘ struct exampleBus { … }; ‘
for exampleBus does not match content
‘ struct exampleBus { … }; ‘
in the shared header file "sharedSimulinkTypes.h".
To continue, either manually remove the Simulink cache files and the slprj folder, or rename these objects.
I identified that the problem is a shared_file.dmr in _sharedutils folder, as deleting that file will allow code generation and sharedSimulinkTypes.h will just be replaced. What is the shared_file.dmr, why is it created and is it necessary? I tried to find a way of disabling the generation of it, or creating a callback before code generation starts to delete the file, but was unsuccessful in finding a way to do that.My physical system (parent model) consists of different smaller subsystems, that all run on separate ECUs, thus are referenced models for separate code generation. All of the subsystems share some buses, which are exported in the global .sldd file, and saved to a file sharedSimulinkTypes.h, which is generated under the _sharedutils folder. When a shared bus is changed, generating code will result in an error, stating:
The contents of the following objects do not match those in the current slprj directory:
Content
‘ struct exampleBus { … }; ‘
for exampleBus does not match content
‘ struct exampleBus { … }; ‘
in the shared header file "sharedSimulinkTypes.h".
To continue, either manually remove the Simulink cache files and the slprj folder, or rename these objects.
I identified that the problem is a shared_file.dmr in _sharedutils folder, as deleting that file will allow code generation and sharedSimulinkTypes.h will just be replaced. What is the shared_file.dmr, why is it created and is it necessary? I tried to find a way of disabling the generation of it, or creating a callback before code generation starts to delete the file, but was unsuccessful in finding a way to do that. My physical system (parent model) consists of different smaller subsystems, that all run on separate ECUs, thus are referenced models for separate code generation. All of the subsystems share some buses, which are exported in the global .sldd file, and saved to a file sharedSimulinkTypes.h, which is generated under the _sharedutils folder. When a shared bus is changed, generating code will result in an error, stating:
The contents of the following objects do not match those in the current slprj directory:
Content
‘ struct exampleBus { … }; ‘
for exampleBus does not match content
‘ struct exampleBus { … }; ‘
in the shared header file "sharedSimulinkTypes.h".
To continue, either manually remove the Simulink cache files and the slprj folder, or rename these objects.
I identified that the problem is a shared_file.dmr in _sharedutils folder, as deleting that file will allow code generation and sharedSimulinkTypes.h will just be replaced. What is the shared_file.dmr, why is it created and is it necessary? I tried to find a way of disabling the generation of it, or creating a callback before code generation starts to delete the file, but was unsuccessful in finding a way to do that. code generation, shared variables MATLAB Answers — New Questions
Issue with Incorrect Graphs Displayed in MATLAB on Linux Mint 22incorrect graph outputs
Hi everyone,
I’ve encountered an issue where the graphs plotted in MATLAB on my system appear incorrect, both in the desktop version and MATLAB Online. However, when I export these graphs to a PDF, the output is correct. I tested the same code on a different machine, and the graphs were displayed correctly without any issues.
Here are some details about my setup:
Operating System: Linux Mint 22
MATLAB version: [Include your MATLAB version here]
The problem occurs in both desktop MATLAB and MATLAB Online.
Exported graphs (e.g., to PDF) show the correct output.
I suspect the issue could be related to my laptop or some specific settings, but I’m not sure where to start. Has anyone experienced a similar issue or have suggestions on how to resolve this?
Thank you in advance for your help!Hi everyone,
I’ve encountered an issue where the graphs plotted in MATLAB on my system appear incorrect, both in the desktop version and MATLAB Online. However, when I export these graphs to a PDF, the output is correct. I tested the same code on a different machine, and the graphs were displayed correctly without any issues.
Here are some details about my setup:
Operating System: Linux Mint 22
MATLAB version: [Include your MATLAB version here]
The problem occurs in both desktop MATLAB and MATLAB Online.
Exported graphs (e.g., to PDF) show the correct output.
I suspect the issue could be related to my laptop or some specific settings, but I’m not sure where to start. Has anyone experienced a similar issue or have suggestions on how to resolve this?
Thank you in advance for your help! Hi everyone,
I’ve encountered an issue where the graphs plotted in MATLAB on my system appear incorrect, both in the desktop version and MATLAB Online. However, when I export these graphs to a PDF, the output is correct. I tested the same code on a different machine, and the graphs were displayed correctly without any issues.
Here are some details about my setup:
Operating System: Linux Mint 22
MATLAB version: [Include your MATLAB version here]
The problem occurs in both desktop MATLAB and MATLAB Online.
Exported graphs (e.g., to PDF) show the correct output.
I suspect the issue could be related to my laptop or some specific settings, but I’m not sure where to start. Has anyone experienced a similar issue or have suggestions on how to resolve this?
Thank you in advance for your help! matlab, graphing, linux mint, fourier transform MATLAB Answers — New Questions
Cannot install Symbolic Math Toolbox.
I’m trying to install Symbolic Math toolbox, and I’m getting a message:
"Errors
Your license data needs to be updated. Contact us to complete this purchase."
I’m a home user so when I tried to contact it said I do not have extended support. I just want to buy symbolic math toolbox and install it.I’m trying to install Symbolic Math toolbox, and I’m getting a message:
"Errors
Your license data needs to be updated. Contact us to complete this purchase."
I’m a home user so when I tried to contact it said I do not have extended support. I just want to buy symbolic math toolbox and install it. I’m trying to install Symbolic Math toolbox, and I’m getting a message:
"Errors
Your license data needs to be updated. Contact us to complete this purchase."
I’m a home user so when I tried to contact it said I do not have extended support. I just want to buy symbolic math toolbox and install it. license, matlab, add-ons MATLAB Answers — New Questions
Writing Hardware Drivers in Simulink — Good Idea?
Hey all, I was hoping to get some feedback on a design philosophy that may or may not be a good idea. For context, I’m an embedded software engineer who’s new to Simulink but fairly experienced with writing hardware drivers in C/C++.
I’ve got a large new project at work (bare metal) that is taking a model based design approach and one engineer (very experienced with Simulink), is advocating strongly for writing the HW drivers in Simulink. I’ve messed around with embedded coder a little bit and see how that could be possible, but my question is: Is this a good idea?
The argument is that by doing everything in Simulink we can take full advantage of the analysis tools built into the product to increase our confidence level in the software correctness, which is actually a very important thing we need in this project. I like the idea of that, however I haven’t seen many references elsewhere on the internet where this is done.Hey all, I was hoping to get some feedback on a design philosophy that may or may not be a good idea. For context, I’m an embedded software engineer who’s new to Simulink but fairly experienced with writing hardware drivers in C/C++.
I’ve got a large new project at work (bare metal) that is taking a model based design approach and one engineer (very experienced with Simulink), is advocating strongly for writing the HW drivers in Simulink. I’ve messed around with embedded coder a little bit and see how that could be possible, but my question is: Is this a good idea?
The argument is that by doing everything in Simulink we can take full advantage of the analysis tools built into the product to increase our confidence level in the software correctness, which is actually a very important thing we need in this project. I like the idea of that, however I haven’t seen many references elsewhere on the internet where this is done. Hey all, I was hoping to get some feedback on a design philosophy that may or may not be a good idea. For context, I’m an embedded software engineer who’s new to Simulink but fairly experienced with writing hardware drivers in C/C++.
I’ve got a large new project at work (bare metal) that is taking a model based design approach and one engineer (very experienced with Simulink), is advocating strongly for writing the HW drivers in Simulink. I’ve messed around with embedded coder a little bit and see how that could be possible, but my question is: Is this a good idea?
The argument is that by doing everything in Simulink we can take full advantage of the analysis tools built into the product to increase our confidence level in the software correctness, which is actually a very important thing we need in this project. I like the idea of that, however I haven’t seen many references elsewhere on the internet where this is done. simulink, embedded coder, hardware, kernel MATLAB Answers — New Questions
plotting functions with two y axes
Hello,
I have to plot two curves on the same graph, same x-axis and different y-axes (right and left). I can’t draw the curves with different hatching, different thickness and same black color. I would also like to insert the title of the axes and the legend. Below is the attempt script (R2021b).
Many thanks for the help
figure(1)
x1 = 0:0.1:10;
y1=10+x1.*4;
x2 = 0:0.1:10;
y2=15*sin(x2/2)
t = tiledlayout(1,1);
ax1 = axes(t);
plot(ax1,x1,y1,’-k’)
ax1.XColor = ‘k’;
ax1.YColor = ‘k’;
ax2 = axes(t);
plot(ax2,x2,y2,’–k’)
ax1.XAxisLocation = ‘bottom’;
ax1.YAxisLocation = ‘left’;
ax2.XAxisLocation = ‘top’;
ax2.YAxisLocation = ‘right’;
ax2.Color = ‘none’;
ax1.Box = ‘off’;
ax2.Box = ‘off’;
gridHello,
I have to plot two curves on the same graph, same x-axis and different y-axes (right and left). I can’t draw the curves with different hatching, different thickness and same black color. I would also like to insert the title of the axes and the legend. Below is the attempt script (R2021b).
Many thanks for the help
figure(1)
x1 = 0:0.1:10;
y1=10+x1.*4;
x2 = 0:0.1:10;
y2=15*sin(x2/2)
t = tiledlayout(1,1);
ax1 = axes(t);
plot(ax1,x1,y1,’-k’)
ax1.XColor = ‘k’;
ax1.YColor = ‘k’;
ax2 = axes(t);
plot(ax2,x2,y2,’–k’)
ax1.XAxisLocation = ‘bottom’;
ax1.YAxisLocation = ‘left’;
ax2.XAxisLocation = ‘top’;
ax2.YAxisLocation = ‘right’;
ax2.Color = ‘none’;
ax1.Box = ‘off’;
ax2.Box = ‘off’;
grid Hello,
I have to plot two curves on the same graph, same x-axis and different y-axes (right and left). I can’t draw the curves with different hatching, different thickness and same black color. I would also like to insert the title of the axes and the legend. Below is the attempt script (R2021b).
Many thanks for the help
figure(1)
x1 = 0:0.1:10;
y1=10+x1.*4;
x2 = 0:0.1:10;
y2=15*sin(x2/2)
t = tiledlayout(1,1);
ax1 = axes(t);
plot(ax1,x1,y1,’-k’)
ax1.XColor = ‘k’;
ax1.YColor = ‘k’;
ax2 = axes(t);
plot(ax2,x2,y2,’–k’)
ax1.XAxisLocation = ‘bottom’;
ax1.YAxisLocation = ‘left’;
ax2.XAxisLocation = ‘top’;
ax2.YAxisLocation = ‘right’;
ax2.Color = ‘none’;
ax1.Box = ‘off’;
ax2.Box = ‘off’;
grid plotting, plot yy MATLAB Answers — New Questions
How to define the abstract symbolic of ‘f=f(x,y,z)’ at Matlab-Smbolic.
I have a black-box function of 3-variables : f=f(x,y,z).
I would like to define with symbolic the relation of ‘f’ with ‘x’,’y’ and ‘z’, as the abstract type of mathematics ‘f=f(x,y,z)’.
In example, I want to do something like:
syms x y z;
_I do not know how to set the symbolic at command line : f=f(x,y,z);
g = x * f + y * f^2 + z;
jacobian( g, [x,y,z])
_and the expected result will be :_
( f + x*(df/dx) + 2*y*f*(df/dx), x*(df/dy) + f^2 + 2*y*f*(df/dy),
x*(df/dz) + 2*y*f*(df/dz) + 1)
Thanks.I have a black-box function of 3-variables : f=f(x,y,z).
I would like to define with symbolic the relation of ‘f’ with ‘x’,’y’ and ‘z’, as the abstract type of mathematics ‘f=f(x,y,z)’.
In example, I want to do something like:
syms x y z;
_I do not know how to set the symbolic at command line : f=f(x,y,z);
g = x * f + y * f^2 + z;
jacobian( g, [x,y,z])
_and the expected result will be :_
( f + x*(df/dx) + 2*y*f*(df/dx), x*(df/dy) + f^2 + 2*y*f*(df/dy),
x*(df/dz) + 2*y*f*(df/dz) + 1)
Thanks. I have a black-box function of 3-variables : f=f(x,y,z).
I would like to define with symbolic the relation of ‘f’ with ‘x’,’y’ and ‘z’, as the abstract type of mathematics ‘f=f(x,y,z)’.
In example, I want to do something like:
syms x y z;
_I do not know how to set the symbolic at command line : f=f(x,y,z);
g = x * f + y * f^2 + z;
jacobian( g, [x,y,z])
_and the expected result will be :_
( f + x*(df/dx) + 2*y*f*(df/dx), x*(df/dy) + f^2 + 2*y*f*(df/dy),
x*(df/dz) + 2*y*f*(df/dz) + 1)
Thanks. symbolic MATLAB Answers — New Questions
How to preserve initial conditions of a model when compiling it as an FMU?
I have a working Simulink model where two of the output signals are passed back into the model as inputs for the next time step.
Currently I am defining the initial conditions inside integrator blocks to avoid algerbraic loop errors which works as expected. The initial conditions are stored as MATLAB variables so I can expose them to the user when compiling the model as a standalone FMU.
However, after compiling the model as a standalone FMU and importing the FMU back into the Simulink environment to test the functionality, I am now seeing algebraic loop errors and discontinuities where previously there weren’t any.
See error messages below for more context.
Discontinuities detected within algebraic loop(s), may have trouble solving.
An error occurred while running the simulation and the simulation was terminated
Caused by: Algebraic state in algebraic loop containing ‘Model_FMU/FMU’ computed at time 0.00082000000000000009 is Inf or NaN. There may be a singularity in the solution. If the model is correct, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances) or tweak the initial guess of algebraic loop variable values.
Is there something I am missing that is changing the behaviour of the model when compiling?
The source of the error may not actually be the initial conditions changing but I am making an assumption based on the error messages.I have a working Simulink model where two of the output signals are passed back into the model as inputs for the next time step.
Currently I am defining the initial conditions inside integrator blocks to avoid algerbraic loop errors which works as expected. The initial conditions are stored as MATLAB variables so I can expose them to the user when compiling the model as a standalone FMU.
However, after compiling the model as a standalone FMU and importing the FMU back into the Simulink environment to test the functionality, I am now seeing algebraic loop errors and discontinuities where previously there weren’t any.
See error messages below for more context.
Discontinuities detected within algebraic loop(s), may have trouble solving.
An error occurred while running the simulation and the simulation was terminated
Caused by: Algebraic state in algebraic loop containing ‘Model_FMU/FMU’ computed at time 0.00082000000000000009 is Inf or NaN. There may be a singularity in the solution. If the model is correct, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances) or tweak the initial guess of algebraic loop variable values.
Is there something I am missing that is changing the behaviour of the model when compiling?
The source of the error may not actually be the initial conditions changing but I am making an assumption based on the error messages. I have a working Simulink model where two of the output signals are passed back into the model as inputs for the next time step.
Currently I am defining the initial conditions inside integrator blocks to avoid algerbraic loop errors which works as expected. The initial conditions are stored as MATLAB variables so I can expose them to the user when compiling the model as a standalone FMU.
However, after compiling the model as a standalone FMU and importing the FMU back into the Simulink environment to test the functionality, I am now seeing algebraic loop errors and discontinuities where previously there weren’t any.
See error messages below for more context.
Discontinuities detected within algebraic loop(s), may have trouble solving.
An error occurred while running the simulation and the simulation was terminated
Caused by: Algebraic state in algebraic loop containing ‘Model_FMU/FMU’ computed at time 0.00082000000000000009 is Inf or NaN. There may be a singularity in the solution. If the model is correct, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances) or tweak the initial guess of algebraic loop variable values.
Is there something I am missing that is changing the behaviour of the model when compiling?
The source of the error may not actually be the initial conditions changing but I am making an assumption based on the error messages. compiler, simulink, model MATLAB Answers — New Questions
FMU as Grey box
Hi,
is it possibile to use a model specified with FMU as a Grey-box?
The goal is to identify params in the FMU https://it.mathworks.com/help/ident/ug/estimating-nonlinear-grey-box-models.html.
We are currently developing FMUs with OpenModelica tool and we need to identify some FMUs parameters..Hi,
is it possibile to use a model specified with FMU as a Grey-box?
The goal is to identify params in the FMU https://it.mathworks.com/help/ident/ug/estimating-nonlinear-grey-box-models.html.
We are currently developing FMUs with OpenModelica tool and we need to identify some FMUs parameters.. Hi,
is it possibile to use a model specified with FMU as a Grey-box?
The goal is to identify params in the FMU https://it.mathworks.com/help/ident/ug/estimating-nonlinear-grey-box-models.html.
We are currently developing FMUs with OpenModelica tool and we need to identify some FMUs parameters.. fmu, identification MATLAB Answers — New Questions
Error while running my Reinforcement learning model in R2021a and observation names not matching the names of the deep neural network (underlined below in the m file)
clc
clear
warning(‘off’,’all’)
mdl = ‘wind_DFIG_RL’;
open_system(mdl)
Ts = 7;%agent time
Tf = 7;% simulation time
set_param(mdl, ‘Solver’, ‘ode23tb’, ‘StopTime’, num2str(Tf))
agentblk = ‘wind_DFIG_RL/DFIG Wind Turbine/Control/Rotor-side Controls/WG_RL1/RL Agent’;
% Define the observation specification obsInfo and action specification actInfo.
numObservations = 4
observationInfo = rlNumericSpec([numObservations 1]);
observationInfo.Name = ‘observations’;
observationInfo.Description = ‘information on error and reference signal’;
% create action info
numActions = 2;
actionInfo = rlNumericSpec([numActions 1]);
actionInfo.Name = ‘vqdRef’;
%define environment
env = rlSimulinkEnv(mdl,agentblk,observationInfo,actionInfo);
%randomize refernce rpm
env.ResetFcn = @(in)localResetFcn(in);
Create Network Architecture and DDPG agent
Set the random seed generator for reproducibility.
rng(0)
First, create a critic deep neural network structure and representation
%critic network
% create a network to be used as underlying critic approximator
L = [400 300]; % number of neurons
statePath = [
imageInputLayer([numObservations 1 1],’Normalization’,’none’,’Name’,’state’)
fullyConnectedLayer(L(1),’Name’,’CriticStateFC1′)
clippedReluLayer(10,’Name’,’CriticClip1′)
fullyConnectedLayer(L(2),’Name’,’CriticStateFC2′)];
actionPath = [
imageInputLayer([numActions 1 1],’Normalization’,’none’,’Name’,’Action’)
fullyConnectedLayer(L(2),’Name’,’CriticActionFC1′)];
commonPath = [
additionLayer(2,’Name’,’add’)
clippedReluLayer(10,’Name’,’CriticCCommonClip’)
fullyConnectedLayer(1,’Name’,’CriticOutput’)];
criticNetwork = layerGraph();
criticNetwork = addLayers(criticNetwork,statePath);
criticNetwork = addLayers(criticNetwork,actionPath);
criticNetwork = addLayers(criticNetwork,commonPath);
criticNetwork = connectLayers(criticNetwork,’CriticStateFC2′,’add/in1′);
criticNetwork = connectLayers(criticNetwork,’CriticActionFC1′,’add/in2′);
plot(criticNetwork);
% view the critic network configuration.
% figure plot(criticNetwork)
Create the critic representations. Use the same network structure for both critics. The Soft Actor Critic (SAC) agent initializes the two networks using different default parameters.
criticOpts = rlRepresentationOptions(‘LearnRate’,1e-3,…
‘GradientThreshold’,1,’L2RegularizationFactor’,1e-4);
critic = rlQValueRepresentation(criticNetwork,observationInfo,actionInfo,…
‘Observation’,{‘4′},’Action’,{‘vqdRef’},criticOpts);
Create an actor deep neural network. Do not add a tanhLayer or scalingLayer in the mean output path. The SAC agent internally transforms the unbounded Gaussian distribution to the bounded distribution to compute the probability density function and entropy properly.
statePath = [
featureInputLayer(numObservations,’Normalization’,’none’,’Name’,’observation’)
fullyConnectedLayer(400, ‘Name’,’commonFC1′)
reluLayer(‘Name’,’CommonRelu’)];
meanPath = [
fullyConnectedLayer(300,’Name’,’MeanFC1′)
reluLayer(‘Name’,’MeanRelu’)
fullyConnectedLayer(numActions,’Name’,’Mean’)
];
stdPath = [
fullyConnectedLayer(300,’Name’,’StdFC1′)
reluLayer(‘Name’,’StdRelu’)
fullyConnectedLayer(numActions,’Name’,’StdFC2′)
softplusLayer(‘Name’,’StandardDeviation’)];
concatPath = concatenationLayer(1,2,’Name’,’GaussianParameters’);
actorNetwork = layerGraph(statePath);
actorNetwork = addLayers(actorNetwork,meanPath);
actorNetwork = addLayers(actorNetwork,stdPath);
actorNetwork = addLayers(actorNetwork,concatPath);
actorNetwork = connectLayers(actorNetwork,’CommonRelu’,’MeanFC1/in’);
actorNetwork = connectLayers(actorNetwork,’CommonRelu’,’StdFC1/in’);
actorNetwork = connectLayers(actorNetwork,’Mean’,’GaussianParameters/in1′);
actorNetwork = connectLayers(actorNetwork,’StandardDeviation’,’GaussianParameters/in2′);
Create a stochastic actor representation using the deep neural network.
plot(actorNetwork)
actorOptions = rlRepresentationOptions(‘Optimizer’,’adam’,’LearnRate’,1e-3,…
‘GradientThreshold’,1,’L2RegularizationFactor’,1e-5);
actor = rlStochasticActorRepresentation(actorNetwork,observationInfo,actionInfo,actorOptions,…
‘Observation’,{‘observation’});
Specify agent options.
agentOptions = rlSACAgentOptions;
agentOptions.SampleTime = Ts;
agentOptions.DiscountFactor = 0.99;
agentOptions.TargetSmoothFactor = 1e-3;
agentOptions.ExperienceBufferLength = 1e6;
agentOptions.MiniBatchSize = 32;
Create SAC agent using actor, critics, and options.
agent_DFIG_WG = rlSACAgent(actor,[critic critic2],agentOptions);
Train Agent
To train the agent, first specify the following training options.
Run each training for at most x episodes, with each episode lasting at most ceil(Tf/Ts) time steps.
Display the training progrQw in the Episode Manager (set the Plots option) and disable the command-line display (set the Verbose option).
Stop training when the agent receives an average cumulative reward greater than -x over ceil(Tf/Ts) consecutive episodes. At this point, the agent can control and reguate the measured signal.
For more information, see rlTrainingOptions.
maxepisodes = 20;
maxsteps = ceil(Tf/Ts);
trainOpts = rlTrainingOptions(…
‘MaxEpisodes’,maxepisodes, …
‘MaxStepsPerEpisode’,maxsteps, …
‘ScoreAveragingWindowLength’,5, …
‘Verbose’,true, …
‘Plots’,’training-progress’,…
‘StopTrainingCriteria’,’AverageReward’,…
‘StopTrainingValue’,480,…
‘Plots’,"training-progress");
doTraining = true; %true or false
if doTraining
% Train the agent.
Trainingstats = train(agent_DFIG_WG,env,trainOpts);
save(‘agent_DFIG_WG.mat’,’agent_DFIG_WG’)
else
% Load pretrained agent for the example.
% load(D:RL filesagent_DFIG_WG.mat’,’agent_DFIG_WG’)
end
Validate Trained Agent
Validate the learned agent against the model by simulation.
simOpts = rlSimulationOptions(‘MaxSteps’,maxsteps);
experiences = sim(env,agent_DFIG_WG,simOpts);clc
clear
warning(‘off’,’all’)
mdl = ‘wind_DFIG_RL’;
open_system(mdl)
Ts = 7;%agent time
Tf = 7;% simulation time
set_param(mdl, ‘Solver’, ‘ode23tb’, ‘StopTime’, num2str(Tf))
agentblk = ‘wind_DFIG_RL/DFIG Wind Turbine/Control/Rotor-side Controls/WG_RL1/RL Agent’;
% Define the observation specification obsInfo and action specification actInfo.
numObservations = 4
observationInfo = rlNumericSpec([numObservations 1]);
observationInfo.Name = ‘observations’;
observationInfo.Description = ‘information on error and reference signal’;
% create action info
numActions = 2;
actionInfo = rlNumericSpec([numActions 1]);
actionInfo.Name = ‘vqdRef’;
%define environment
env = rlSimulinkEnv(mdl,agentblk,observationInfo,actionInfo);
%randomize refernce rpm
env.ResetFcn = @(in)localResetFcn(in);
Create Network Architecture and DDPG agent
Set the random seed generator for reproducibility.
rng(0)
First, create a critic deep neural network structure and representation
%critic network
% create a network to be used as underlying critic approximator
L = [400 300]; % number of neurons
statePath = [
imageInputLayer([numObservations 1 1],’Normalization’,’none’,’Name’,’state’)
fullyConnectedLayer(L(1),’Name’,’CriticStateFC1′)
clippedReluLayer(10,’Name’,’CriticClip1′)
fullyConnectedLayer(L(2),’Name’,’CriticStateFC2′)];
actionPath = [
imageInputLayer([numActions 1 1],’Normalization’,’none’,’Name’,’Action’)
fullyConnectedLayer(L(2),’Name’,’CriticActionFC1′)];
commonPath = [
additionLayer(2,’Name’,’add’)
clippedReluLayer(10,’Name’,’CriticCCommonClip’)
fullyConnectedLayer(1,’Name’,’CriticOutput’)];
criticNetwork = layerGraph();
criticNetwork = addLayers(criticNetwork,statePath);
criticNetwork = addLayers(criticNetwork,actionPath);
criticNetwork = addLayers(criticNetwork,commonPath);
criticNetwork = connectLayers(criticNetwork,’CriticStateFC2′,’add/in1′);
criticNetwork = connectLayers(criticNetwork,’CriticActionFC1′,’add/in2′);
plot(criticNetwork);
% view the critic network configuration.
% figure plot(criticNetwork)
Create the critic representations. Use the same network structure for both critics. The Soft Actor Critic (SAC) agent initializes the two networks using different default parameters.
criticOpts = rlRepresentationOptions(‘LearnRate’,1e-3,…
‘GradientThreshold’,1,’L2RegularizationFactor’,1e-4);
critic = rlQValueRepresentation(criticNetwork,observationInfo,actionInfo,…
‘Observation’,{‘4′},’Action’,{‘vqdRef’},criticOpts);
Create an actor deep neural network. Do not add a tanhLayer or scalingLayer in the mean output path. The SAC agent internally transforms the unbounded Gaussian distribution to the bounded distribution to compute the probability density function and entropy properly.
statePath = [
featureInputLayer(numObservations,’Normalization’,’none’,’Name’,’observation’)
fullyConnectedLayer(400, ‘Name’,’commonFC1′)
reluLayer(‘Name’,’CommonRelu’)];
meanPath = [
fullyConnectedLayer(300,’Name’,’MeanFC1′)
reluLayer(‘Name’,’MeanRelu’)
fullyConnectedLayer(numActions,’Name’,’Mean’)
];
stdPath = [
fullyConnectedLayer(300,’Name’,’StdFC1′)
reluLayer(‘Name’,’StdRelu’)
fullyConnectedLayer(numActions,’Name’,’StdFC2′)
softplusLayer(‘Name’,’StandardDeviation’)];
concatPath = concatenationLayer(1,2,’Name’,’GaussianParameters’);
actorNetwork = layerGraph(statePath);
actorNetwork = addLayers(actorNetwork,meanPath);
actorNetwork = addLayers(actorNetwork,stdPath);
actorNetwork = addLayers(actorNetwork,concatPath);
actorNetwork = connectLayers(actorNetwork,’CommonRelu’,’MeanFC1/in’);
actorNetwork = connectLayers(actorNetwork,’CommonRelu’,’StdFC1/in’);
actorNetwork = connectLayers(actorNetwork,’Mean’,’GaussianParameters/in1′);
actorNetwork = connectLayers(actorNetwork,’StandardDeviation’,’GaussianParameters/in2′);
Create a stochastic actor representation using the deep neural network.
plot(actorNetwork)
actorOptions = rlRepresentationOptions(‘Optimizer’,’adam’,’LearnRate’,1e-3,…
‘GradientThreshold’,1,’L2RegularizationFactor’,1e-5);
actor = rlStochasticActorRepresentation(actorNetwork,observationInfo,actionInfo,actorOptions,…
‘Observation’,{‘observation’});
Specify agent options.
agentOptions = rlSACAgentOptions;
agentOptions.SampleTime = Ts;
agentOptions.DiscountFactor = 0.99;
agentOptions.TargetSmoothFactor = 1e-3;
agentOptions.ExperienceBufferLength = 1e6;
agentOptions.MiniBatchSize = 32;
Create SAC agent using actor, critics, and options.
agent_DFIG_WG = rlSACAgent(actor,[critic critic2],agentOptions);
Train Agent
To train the agent, first specify the following training options.
Run each training for at most x episodes, with each episode lasting at most ceil(Tf/Ts) time steps.
Display the training progrQw in the Episode Manager (set the Plots option) and disable the command-line display (set the Verbose option).
Stop training when the agent receives an average cumulative reward greater than -x over ceil(Tf/Ts) consecutive episodes. At this point, the agent can control and reguate the measured signal.
For more information, see rlTrainingOptions.
maxepisodes = 20;
maxsteps = ceil(Tf/Ts);
trainOpts = rlTrainingOptions(…
‘MaxEpisodes’,maxepisodes, …
‘MaxStepsPerEpisode’,maxsteps, …
‘ScoreAveragingWindowLength’,5, …
‘Verbose’,true, …
‘Plots’,’training-progress’,…
‘StopTrainingCriteria’,’AverageReward’,…
‘StopTrainingValue’,480,…
‘Plots’,"training-progress");
doTraining = true; %true or false
if doTraining
% Train the agent.
Trainingstats = train(agent_DFIG_WG,env,trainOpts);
save(‘agent_DFIG_WG.mat’,’agent_DFIG_WG’)
else
% Load pretrained agent for the example.
% load(D:RL filesagent_DFIG_WG.mat’,’agent_DFIG_WG’)
end
Validate Trained Agent
Validate the learned agent against the model by simulation.
simOpts = rlSimulationOptions(‘MaxSteps’,maxsteps);
experiences = sim(env,agent_DFIG_WG,simOpts); clc
clear
warning(‘off’,’all’)
mdl = ‘wind_DFIG_RL’;
open_system(mdl)
Ts = 7;%agent time
Tf = 7;% simulation time
set_param(mdl, ‘Solver’, ‘ode23tb’, ‘StopTime’, num2str(Tf))
agentblk = ‘wind_DFIG_RL/DFIG Wind Turbine/Control/Rotor-side Controls/WG_RL1/RL Agent’;
% Define the observation specification obsInfo and action specification actInfo.
numObservations = 4
observationInfo = rlNumericSpec([numObservations 1]);
observationInfo.Name = ‘observations’;
observationInfo.Description = ‘information on error and reference signal’;
% create action info
numActions = 2;
actionInfo = rlNumericSpec([numActions 1]);
actionInfo.Name = ‘vqdRef’;
%define environment
env = rlSimulinkEnv(mdl,agentblk,observationInfo,actionInfo);
%randomize refernce rpm
env.ResetFcn = @(in)localResetFcn(in);
Create Network Architecture and DDPG agent
Set the random seed generator for reproducibility.
rng(0)
First, create a critic deep neural network structure and representation
%critic network
% create a network to be used as underlying critic approximator
L = [400 300]; % number of neurons
statePath = [
imageInputLayer([numObservations 1 1],’Normalization’,’none’,’Name’,’state’)
fullyConnectedLayer(L(1),’Name’,’CriticStateFC1′)
clippedReluLayer(10,’Name’,’CriticClip1′)
fullyConnectedLayer(L(2),’Name’,’CriticStateFC2′)];
actionPath = [
imageInputLayer([numActions 1 1],’Normalization’,’none’,’Name’,’Action’)
fullyConnectedLayer(L(2),’Name’,’CriticActionFC1′)];
commonPath = [
additionLayer(2,’Name’,’add’)
clippedReluLayer(10,’Name’,’CriticCCommonClip’)
fullyConnectedLayer(1,’Name’,’CriticOutput’)];
criticNetwork = layerGraph();
criticNetwork = addLayers(criticNetwork,statePath);
criticNetwork = addLayers(criticNetwork,actionPath);
criticNetwork = addLayers(criticNetwork,commonPath);
criticNetwork = connectLayers(criticNetwork,’CriticStateFC2′,’add/in1′);
criticNetwork = connectLayers(criticNetwork,’CriticActionFC1′,’add/in2′);
plot(criticNetwork);
% view the critic network configuration.
% figure plot(criticNetwork)
Create the critic representations. Use the same network structure for both critics. The Soft Actor Critic (SAC) agent initializes the two networks using different default parameters.
criticOpts = rlRepresentationOptions(‘LearnRate’,1e-3,…
‘GradientThreshold’,1,’L2RegularizationFactor’,1e-4);
critic = rlQValueRepresentation(criticNetwork,observationInfo,actionInfo,…
‘Observation’,{‘4′},’Action’,{‘vqdRef’},criticOpts);
Create an actor deep neural network. Do not add a tanhLayer or scalingLayer in the mean output path. The SAC agent internally transforms the unbounded Gaussian distribution to the bounded distribution to compute the probability density function and entropy properly.
statePath = [
featureInputLayer(numObservations,’Normalization’,’none’,’Name’,’observation’)
fullyConnectedLayer(400, ‘Name’,’commonFC1′)
reluLayer(‘Name’,’CommonRelu’)];
meanPath = [
fullyConnectedLayer(300,’Name’,’MeanFC1′)
reluLayer(‘Name’,’MeanRelu’)
fullyConnectedLayer(numActions,’Name’,’Mean’)
];
stdPath = [
fullyConnectedLayer(300,’Name’,’StdFC1′)
reluLayer(‘Name’,’StdRelu’)
fullyConnectedLayer(numActions,’Name’,’StdFC2′)
softplusLayer(‘Name’,’StandardDeviation’)];
concatPath = concatenationLayer(1,2,’Name’,’GaussianParameters’);
actorNetwork = layerGraph(statePath);
actorNetwork = addLayers(actorNetwork,meanPath);
actorNetwork = addLayers(actorNetwork,stdPath);
actorNetwork = addLayers(actorNetwork,concatPath);
actorNetwork = connectLayers(actorNetwork,’CommonRelu’,’MeanFC1/in’);
actorNetwork = connectLayers(actorNetwork,’CommonRelu’,’StdFC1/in’);
actorNetwork = connectLayers(actorNetwork,’Mean’,’GaussianParameters/in1′);
actorNetwork = connectLayers(actorNetwork,’StandardDeviation’,’GaussianParameters/in2′);
Create a stochastic actor representation using the deep neural network.
plot(actorNetwork)
actorOptions = rlRepresentationOptions(‘Optimizer’,’adam’,’LearnRate’,1e-3,…
‘GradientThreshold’,1,’L2RegularizationFactor’,1e-5);
actor = rlStochasticActorRepresentation(actorNetwork,observationInfo,actionInfo,actorOptions,…
‘Observation’,{‘observation’});
Specify agent options.
agentOptions = rlSACAgentOptions;
agentOptions.SampleTime = Ts;
agentOptions.DiscountFactor = 0.99;
agentOptions.TargetSmoothFactor = 1e-3;
agentOptions.ExperienceBufferLength = 1e6;
agentOptions.MiniBatchSize = 32;
Create SAC agent using actor, critics, and options.
agent_DFIG_WG = rlSACAgent(actor,[critic critic2],agentOptions);
Train Agent
To train the agent, first specify the following training options.
Run each training for at most x episodes, with each episode lasting at most ceil(Tf/Ts) time steps.
Display the training progrQw in the Episode Manager (set the Plots option) and disable the command-line display (set the Verbose option).
Stop training when the agent receives an average cumulative reward greater than -x over ceil(Tf/Ts) consecutive episodes. At this point, the agent can control and reguate the measured signal.
For more information, see rlTrainingOptions.
maxepisodes = 20;
maxsteps = ceil(Tf/Ts);
trainOpts = rlTrainingOptions(…
‘MaxEpisodes’,maxepisodes, …
‘MaxStepsPerEpisode’,maxsteps, …
‘ScoreAveragingWindowLength’,5, …
‘Verbose’,true, …
‘Plots’,’training-progress’,…
‘StopTrainingCriteria’,’AverageReward’,…
‘StopTrainingValue’,480,…
‘Plots’,"training-progress");
doTraining = true; %true or false
if doTraining
% Train the agent.
Trainingstats = train(agent_DFIG_WG,env,trainOpts);
save(‘agent_DFIG_WG.mat’,’agent_DFIG_WG’)
else
% Load pretrained agent for the example.
% load(D:RL filesagent_DFIG_WG.mat’,’agent_DFIG_WG’)
end
Validate Trained Agent
Validate the learned agent against the model by simulation.
simOpts = rlSimulationOptions(‘MaxSteps’,maxsteps);
experiences = sim(env,agent_DFIG_WG,simOpts); dfig rl, r2021a MATLAB Answers — New Questions
FMU export and import
Hi
I am trying to understand how to use FMU and have created a model and exported it as an FMU and the import it again using a FMU import block. I get the modell to work but when looking at the block parameters for the FMU it says there are "No data to dispay" for Parameters and for input ant output is says "This block contains no structured input/output ports." I can not see the parameters in the XML file either so i can not change the variability in the XML-file.
Why are not any parameters visible as a block parameter or in the XML and what does it mean that the block does not contain any structures inputs/output port?
Does the inputs/outputs need to be declared in some specific way before exporting the FMU?
Is it possible to change the visibility or tunability of parameters in the modell before exporting it as a FMU?
Kind regards Adam JohanssonHi
I am trying to understand how to use FMU and have created a model and exported it as an FMU and the import it again using a FMU import block. I get the modell to work but when looking at the block parameters for the FMU it says there are "No data to dispay" for Parameters and for input ant output is says "This block contains no structured input/output ports." I can not see the parameters in the XML file either so i can not change the variability in the XML-file.
Why are not any parameters visible as a block parameter or in the XML and what does it mean that the block does not contain any structures inputs/output port?
Does the inputs/outputs need to be declared in some specific way before exporting the FMU?
Is it possible to change the visibility or tunability of parameters in the modell before exporting it as a FMU?
Kind regards Adam Johansson Hi
I am trying to understand how to use FMU and have created a model and exported it as an FMU and the import it again using a FMU import block. I get the modell to work but when looking at the block parameters for the FMU it says there are "No data to dispay" for Parameters and for input ant output is says "This block contains no structured input/output ports." I can not see the parameters in the XML file either so i can not change the variability in the XML-file.
Why are not any parameters visible as a block parameter or in the XML and what does it mean that the block does not contain any structures inputs/output port?
Does the inputs/outputs need to be declared in some specific way before exporting the FMU?
Is it possible to change the visibility or tunability of parameters in the modell before exporting it as a FMU?
Kind regards Adam Johansson fmu, fmu parameters, fmu unput MATLAB Answers — New Questions
Get Simulink Coder executable to communicate with other running processes using input and output streams in R2018b
I would like to get the executable I generate from Simulink Coder to communicate with a different process I have running on my machine. I have a executable program we created independently and I would like this program to send inputs to and read outputs from the executable generated from my Simulink model using Simulink Coder. I was wondering if I could use a process similar to input and output streams as in the following link:
https://man7.org/linux/man-pages/man3/popen.3.htmlI would like to get the executable I generate from Simulink Coder to communicate with a different process I have running on my machine. I have a executable program we created independently and I would like this program to send inputs to and read outputs from the executable generated from my Simulink model using Simulink Coder. I was wondering if I could use a process similar to input and output streams as in the following link:
https://man7.org/linux/man-pages/man3/popen.3.html I would like to get the executable I generate from Simulink Coder to communicate with a different process I have running on my machine. I have a executable program we created independently and I would like this program to send inputs to and read outputs from the executable generated from my Simulink model using Simulink Coder. I was wondering if I could use a process similar to input and output streams as in the following link:
https://man7.org/linux/man-pages/man3/popen.3.html MATLAB Answers — New Questions
How does the new File Log block work in R2020b and later, and how is it different from the old File Scope block in Simulink Real-Time?
The File Scope block, as well as the "simulinkrealtime.filescope" object, do not appear to be available anymore in Simulink Real-Time R2020b and beyond. How can I do signal logging on my Speedgoat target in R2020b and beyond?The File Scope block, as well as the "simulinkrealtime.filescope" object, do not appear to be available anymore in Simulink Real-Time R2020b and beyond. How can I do signal logging on my Speedgoat target in R2020b and beyond? The File Scope block, as well as the "simulinkrealtime.filescope" object, do not appear to be available anymore in Simulink Real-Time R2020b and beyond. How can I do signal logging on my Speedgoat target in R2020b and beyond? slrt, speedgoat, logging, data MATLAB Answers — New Questions
Mathematics for Engineers: The Capstone Course, Assignment 2
function omega = flow_around_cylinder_unsteady
Re=60;
%%%%% define the grid %%%%%
n=101; m=202; % number of grid points
N=n-1; M=m-2; % number of grid intervals: 2 ghost points, theta=-h,2*pi
h=2*pi/M; % grid spacing based on theta variable
xi=(0:N)*h; theta=(-1:M)*h; % xi and theta variables on the grid
%%%%% time-stepping parameters %%%%%
t_start=0; t_end=0.5; %vortex street starts at around t=1000
tspan=[t_start t_end];
%%%%% Initialize vorticity field %%%%%
omega=zeros(n,m);
%%%%% Construct the matrix A for psi equation %%%%%
boundary_index_bottom = 1:n;
boundary_index_left = 1:n:1+(m-1)*n;
boundary_index_top = 1+(m-1)*n:m*n;
boundary_index_right = n:n:m*n;
diagonals1 = [4*ones(n*m,1), -ones(n*m,4)];
A=spdiags(diagonals1,[0 -1 1 -n n], n*m, n*m);
I=speye(m*n);
A(boundary_index_left,:)=I(boundary_index_left,:);
A(boundary_index_right,:)=I(boundary_index_right,:);
diagonals2 = [ones(n*m,1), -ones(n*m,2)];
Aux = spdiags(diagonals2,[0 n -n],n*m,n*m);
A(boundary_index_top,:)=Aux(boundary_index_top,:);
A(boundary_index_bottom,:)=Aux(boundary_index_bottom,:);
%%%%% Find the LU decomposition %%%%%
[L,U]=lu(A); clear A;
%%%%% Compute any time-independent constants %%%%%
%%%%% advance solution using ode23 %%%%%
options=odeset(‘RelTol’, 1.e-03);
omega=omega(2:n-1,2:m-1); % strip boundary values for ode23
omega=omega(:); % make a column vector
[t,omega]=ode23…
(@(t,omega)omega_eq(omega,L,U, theta, xi, h, Re, n, m),…
tspan, omega, options);
%%%%% expand omega to include boundaries %%%%%
temp=zeros(n,m);
temp(2:n-1,2:m-1)=reshape(omega(end,:),n-2,m-2);
omega=temp; clear temp;
%%%%% compute stream function (needed for omega boundary values) %%%%%
omega_tilde = zeros(n, m);
omega_tilde(1, 🙂 = 0;
omega_tilde(n, 🙂 = exp(xi(n)) * sin(theta);
omega_tilde(:, 1) = 0;
omega_tilde(:, m) = 0;
for i = 2:n-1
for j = 2:m-1
omega_tilde(i, j) = h^2 * exp(2 * xi(i)) * omega(i, j);
end
end
omega_tilde = omega_tilde(:);
psi = reshape(U (L omega_tilde), n, m);
%%%%% set omega boundary conditions %%%%%
omega(1, 🙂 = (psi(3, 🙂 – 8 * psi(2, :)) * 1 / (2 * h^2);
omega(n, 🙂 = 0;
omega(:, 1) = omega(:, m-1);
omega(:, m) = omega(:, 2);
%%%%% plot scalar vorticity field %%%%%
plot_Re60(omega,t_end);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function d_omega_dt=omega_eq(omega,L,U,theta, xi, h, Re, n, m)
%%%%% expand omega to include boundary points %%%%%
temp=zeros(n,m);
index1=2:n-1; index2=2:m-1;
temp(index1,index2)=reshape(omega,n-2,m-2);
omega=temp; clear temp;
%%%%% compute stream function %%%%%
omega_tilde = zeros(n, m);
omega_tilde(1, 🙂 = 0;
omega_tilde(n, 🙂 = exp(xi(n)) * sin(theta);
omega_tilde(:, 1) = 0;
omega_tilde(:, m) = 0;
for i = 2:n-1
for j = 2:m-1
omega_tilde(i, j) = h^2 * exp(2 * xi(i)) * omega(i, j);
end
end
omega_tilde = omega_tilde(:);
psi = reshape(U (L omega_tilde), n, m);
%%%%% compute derivatives of omega %%%%%
omega(1, 🙂 = (psi(3, 🙂 – 8 * psi(2, :)) * 1 / (2 * h^2);
omega(n, 🙂 = 0;
omega(:, 1) = omega(:, m-1);
omega(:, m) = omega(:, 2);
d_omega_dt = zeros(n-2, m-2);
for i = 2:n-1
for j = 2:m-1
d_omega_dt(i-1, j-1) = …
2 * exp(-2 * xi(i)) * 1 / (h^2 * Re) * …
(omega(i+1, j) + omega(i-1, j) + omega(i, j+1) + omega(i, j-1) – 4 * omega(i, j)) …
+ exp(-2 * xi(i)) / (4 * h^2) * …
((psi(i+1, j) – psi(i-1, j)) * (omega(i, j+1) – omega(i, j-1)) – …
(psi(i, j+1) – psi(i, j-1)) * (omega(i+1, j) – omega(i-1, j)));
end
end
d_omega_dt = d_omega_dt(:);
endfunction omega = flow_around_cylinder_unsteady
Re=60;
%%%%% define the grid %%%%%
n=101; m=202; % number of grid points
N=n-1; M=m-2; % number of grid intervals: 2 ghost points, theta=-h,2*pi
h=2*pi/M; % grid spacing based on theta variable
xi=(0:N)*h; theta=(-1:M)*h; % xi and theta variables on the grid
%%%%% time-stepping parameters %%%%%
t_start=0; t_end=0.5; %vortex street starts at around t=1000
tspan=[t_start t_end];
%%%%% Initialize vorticity field %%%%%
omega=zeros(n,m);
%%%%% Construct the matrix A for psi equation %%%%%
boundary_index_bottom = 1:n;
boundary_index_left = 1:n:1+(m-1)*n;
boundary_index_top = 1+(m-1)*n:m*n;
boundary_index_right = n:n:m*n;
diagonals1 = [4*ones(n*m,1), -ones(n*m,4)];
A=spdiags(diagonals1,[0 -1 1 -n n], n*m, n*m);
I=speye(m*n);
A(boundary_index_left,:)=I(boundary_index_left,:);
A(boundary_index_right,:)=I(boundary_index_right,:);
diagonals2 = [ones(n*m,1), -ones(n*m,2)];
Aux = spdiags(diagonals2,[0 n -n],n*m,n*m);
A(boundary_index_top,:)=Aux(boundary_index_top,:);
A(boundary_index_bottom,:)=Aux(boundary_index_bottom,:);
%%%%% Find the LU decomposition %%%%%
[L,U]=lu(A); clear A;
%%%%% Compute any time-independent constants %%%%%
%%%%% advance solution using ode23 %%%%%
options=odeset(‘RelTol’, 1.e-03);
omega=omega(2:n-1,2:m-1); % strip boundary values for ode23
omega=omega(:); % make a column vector
[t,omega]=ode23…
(@(t,omega)omega_eq(omega,L,U, theta, xi, h, Re, n, m),…
tspan, omega, options);
%%%%% expand omega to include boundaries %%%%%
temp=zeros(n,m);
temp(2:n-1,2:m-1)=reshape(omega(end,:),n-2,m-2);
omega=temp; clear temp;
%%%%% compute stream function (needed for omega boundary values) %%%%%
omega_tilde = zeros(n, m);
omega_tilde(1, 🙂 = 0;
omega_tilde(n, 🙂 = exp(xi(n)) * sin(theta);
omega_tilde(:, 1) = 0;
omega_tilde(:, m) = 0;
for i = 2:n-1
for j = 2:m-1
omega_tilde(i, j) = h^2 * exp(2 * xi(i)) * omega(i, j);
end
end
omega_tilde = omega_tilde(:);
psi = reshape(U (L omega_tilde), n, m);
%%%%% set omega boundary conditions %%%%%
omega(1, 🙂 = (psi(3, 🙂 – 8 * psi(2, :)) * 1 / (2 * h^2);
omega(n, 🙂 = 0;
omega(:, 1) = omega(:, m-1);
omega(:, m) = omega(:, 2);
%%%%% plot scalar vorticity field %%%%%
plot_Re60(omega,t_end);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function d_omega_dt=omega_eq(omega,L,U,theta, xi, h, Re, n, m)
%%%%% expand omega to include boundary points %%%%%
temp=zeros(n,m);
index1=2:n-1; index2=2:m-1;
temp(index1,index2)=reshape(omega,n-2,m-2);
omega=temp; clear temp;
%%%%% compute stream function %%%%%
omega_tilde = zeros(n, m);
omega_tilde(1, 🙂 = 0;
omega_tilde(n, 🙂 = exp(xi(n)) * sin(theta);
omega_tilde(:, 1) = 0;
omega_tilde(:, m) = 0;
for i = 2:n-1
for j = 2:m-1
omega_tilde(i, j) = h^2 * exp(2 * xi(i)) * omega(i, j);
end
end
omega_tilde = omega_tilde(:);
psi = reshape(U (L omega_tilde), n, m);
%%%%% compute derivatives of omega %%%%%
omega(1, 🙂 = (psi(3, 🙂 – 8 * psi(2, :)) * 1 / (2 * h^2);
omega(n, 🙂 = 0;
omega(:, 1) = omega(:, m-1);
omega(:, m) = omega(:, 2);
d_omega_dt = zeros(n-2, m-2);
for i = 2:n-1
for j = 2:m-1
d_omega_dt(i-1, j-1) = …
2 * exp(-2 * xi(i)) * 1 / (h^2 * Re) * …
(omega(i+1, j) + omega(i-1, j) + omega(i, j+1) + omega(i, j-1) – 4 * omega(i, j)) …
+ exp(-2 * xi(i)) / (4 * h^2) * …
((psi(i+1, j) – psi(i-1, j)) * (omega(i, j+1) – omega(i, j-1)) – …
(psi(i, j+1) – psi(i, j-1)) * (omega(i+1, j) – omega(i-1, j)));
end
end
d_omega_dt = d_omega_dt(:);
end function omega = flow_around_cylinder_unsteady
Re=60;
%%%%% define the grid %%%%%
n=101; m=202; % number of grid points
N=n-1; M=m-2; % number of grid intervals: 2 ghost points, theta=-h,2*pi
h=2*pi/M; % grid spacing based on theta variable
xi=(0:N)*h; theta=(-1:M)*h; % xi and theta variables on the grid
%%%%% time-stepping parameters %%%%%
t_start=0; t_end=0.5; %vortex street starts at around t=1000
tspan=[t_start t_end];
%%%%% Initialize vorticity field %%%%%
omega=zeros(n,m);
%%%%% Construct the matrix A for psi equation %%%%%
boundary_index_bottom = 1:n;
boundary_index_left = 1:n:1+(m-1)*n;
boundary_index_top = 1+(m-1)*n:m*n;
boundary_index_right = n:n:m*n;
diagonals1 = [4*ones(n*m,1), -ones(n*m,4)];
A=spdiags(diagonals1,[0 -1 1 -n n], n*m, n*m);
I=speye(m*n);
A(boundary_index_left,:)=I(boundary_index_left,:);
A(boundary_index_right,:)=I(boundary_index_right,:);
diagonals2 = [ones(n*m,1), -ones(n*m,2)];
Aux = spdiags(diagonals2,[0 n -n],n*m,n*m);
A(boundary_index_top,:)=Aux(boundary_index_top,:);
A(boundary_index_bottom,:)=Aux(boundary_index_bottom,:);
%%%%% Find the LU decomposition %%%%%
[L,U]=lu(A); clear A;
%%%%% Compute any time-independent constants %%%%%
%%%%% advance solution using ode23 %%%%%
options=odeset(‘RelTol’, 1.e-03);
omega=omega(2:n-1,2:m-1); % strip boundary values for ode23
omega=omega(:); % make a column vector
[t,omega]=ode23…
(@(t,omega)omega_eq(omega,L,U, theta, xi, h, Re, n, m),…
tspan, omega, options);
%%%%% expand omega to include boundaries %%%%%
temp=zeros(n,m);
temp(2:n-1,2:m-1)=reshape(omega(end,:),n-2,m-2);
omega=temp; clear temp;
%%%%% compute stream function (needed for omega boundary values) %%%%%
omega_tilde = zeros(n, m);
omega_tilde(1, 🙂 = 0;
omega_tilde(n, 🙂 = exp(xi(n)) * sin(theta);
omega_tilde(:, 1) = 0;
omega_tilde(:, m) = 0;
for i = 2:n-1
for j = 2:m-1
omega_tilde(i, j) = h^2 * exp(2 * xi(i)) * omega(i, j);
end
end
omega_tilde = omega_tilde(:);
psi = reshape(U (L omega_tilde), n, m);
%%%%% set omega boundary conditions %%%%%
omega(1, 🙂 = (psi(3, 🙂 – 8 * psi(2, :)) * 1 / (2 * h^2);
omega(n, 🙂 = 0;
omega(:, 1) = omega(:, m-1);
omega(:, m) = omega(:, 2);
%%%%% plot scalar vorticity field %%%%%
plot_Re60(omega,t_end);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function d_omega_dt=omega_eq(omega,L,U,theta, xi, h, Re, n, m)
%%%%% expand omega to include boundary points %%%%%
temp=zeros(n,m);
index1=2:n-1; index2=2:m-1;
temp(index1,index2)=reshape(omega,n-2,m-2);
omega=temp; clear temp;
%%%%% compute stream function %%%%%
omega_tilde = zeros(n, m);
omega_tilde(1, 🙂 = 0;
omega_tilde(n, 🙂 = exp(xi(n)) * sin(theta);
omega_tilde(:, 1) = 0;
omega_tilde(:, m) = 0;
for i = 2:n-1
for j = 2:m-1
omega_tilde(i, j) = h^2 * exp(2 * xi(i)) * omega(i, j);
end
end
omega_tilde = omega_tilde(:);
psi = reshape(U (L omega_tilde), n, m);
%%%%% compute derivatives of omega %%%%%
omega(1, 🙂 = (psi(3, 🙂 – 8 * psi(2, :)) * 1 / (2 * h^2);
omega(n, 🙂 = 0;
omega(:, 1) = omega(:, m-1);
omega(:, m) = omega(:, 2);
d_omega_dt = zeros(n-2, m-2);
for i = 2:n-1
for j = 2:m-1
d_omega_dt(i-1, j-1) = …
2 * exp(-2 * xi(i)) * 1 / (h^2 * Re) * …
(omega(i+1, j) + omega(i-1, j) + omega(i, j+1) + omega(i, j-1) – 4 * omega(i, j)) …
+ exp(-2 * xi(i)) / (4 * h^2) * …
((psi(i+1, j) – psi(i-1, j)) * (omega(i, j+1) – omega(i, j-1)) – …
(psi(i, j+1) – psi(i, j-1)) * (omega(i+1, j) – omega(i-1, j)));
end
end
d_omega_dt = d_omega_dt(:);
end vorticity, 2dimension MATLAB Answers — New Questions
I change the arrival time in the entity generator but the scope for entities departured stay the same (simulink)
In the entity generator block, I have changed the source to matlab action and in the insert pattern I have put exponential. I am assuming by setting the mean to 5 this means that 5 entities arrive in each time unit. In the statistics I have enabled the number of departed entities and connected it with a scope. I change the mean from 5 to 0.5 or 1 or whatever and the scope still stays the same. Is this some bug or I am doing something wrong? I tested this both on online simulink and on my downloaded matlab and the result is the same.In the entity generator block, I have changed the source to matlab action and in the insert pattern I have put exponential. I am assuming by setting the mean to 5 this means that 5 entities arrive in each time unit. In the statistics I have enabled the number of departed entities and connected it with a scope. I change the mean from 5 to 0.5 or 1 or whatever and the scope still stays the same. Is this some bug or I am doing something wrong? I tested this both on online simulink and on my downloaded matlab and the result is the same. In the entity generator block, I have changed the source to matlab action and in the insert pattern I have put exponential. I am assuming by setting the mean to 5 this means that 5 entities arrive in each time unit. In the statistics I have enabled the number of departed entities and connected it with a scope. I change the mean from 5 to 0.5 or 1 or whatever and the scope still stays the same. Is this some bug or I am doing something wrong? I tested this both on online simulink and on my downloaded matlab and the result is the same. entitygenerator, arrivaltime, simulink, exponential MATLAB Answers — New Questions