Author: PuTI
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
simulink 如何封装成可脱离Matlab环境的可执行文件
我的simulink模型中有一部分是dymola建立的模型,通过FMU导入的,一部分是利用M文件编写的s-function用于matlab和REDIS数据库交换数据,这样的simulink模型,能否生存脱离matlab运行的可执行文件?如何操作?需要什么toolbox?我的simulink模型中有一部分是dymola建立的模型,通过FMU导入的,一部分是利用M文件编写的s-function用于matlab和REDIS数据库交换数据,这样的simulink模型,能否生存脱离matlab运行的可执行文件?如何操作?需要什么toolbox? 我的simulink模型中有一部分是dymola建立的模型,通过FMU导入的,一部分是利用M文件编写的s-function用于matlab和REDIS数据库交换数据,这样的simulink模型,能否生存脱离matlab运行的可执行文件?如何操作?需要什么toolbox? simulink 封装成可执行文件 MATLAB Answers — New Questions
Why is there a huge drop in the values of active and reactive power when the voltage of three phase voltage source is changed?
Hi Community,
I have modelled a grid using a programmable three phase voltage source and there are three loads attached to it. Model & Parameter file is attached. Each load is defined by the rated active and reactive powers (P& Q) as follows –
Load 1: Rated P = 25 kW; Rated Q = 5 kVA
Load 2: Rated P = 30 kW; rated Q = 10 kVA
Load 3: Rated P = 125 kW; rated Q = 10 kVA
The loads 2 and 3 are switched off at T = 2 secs and switched back on at T = 4 secs. I am also measuring the powers at each of the individual loads as well as the total power supplied by grid.
When I use the voltage source rating = 2300V, the P & Q values are nearly the same (but not exact match) as the above specified parameters.
When I use voltage source = 400V (with everything else remaining the same) there is a huge drop in the measured P & Q values and I am unable to follow why is this happening?
Q1) Why are the measured P&Q so low for V = 400V vs V = 2300V? Is there some limitation on the power this grid can deliver? If yes, then how is this being limited and how can I determine what is the maximum power rating of the load that can be connected across this grid source?
Q2) Additionally in the first scenario with 2300V why are the measured P&Q not the exact match of rated power of loads slightly lesser. I assume some power is lost in "losses" but I canot figure out where are these losses happening?Hi Community,
I have modelled a grid using a programmable three phase voltage source and there are three loads attached to it. Model & Parameter file is attached. Each load is defined by the rated active and reactive powers (P& Q) as follows –
Load 1: Rated P = 25 kW; Rated Q = 5 kVA
Load 2: Rated P = 30 kW; rated Q = 10 kVA
Load 3: Rated P = 125 kW; rated Q = 10 kVA
The loads 2 and 3 are switched off at T = 2 secs and switched back on at T = 4 secs. I am also measuring the powers at each of the individual loads as well as the total power supplied by grid.
When I use the voltage source rating = 2300V, the P & Q values are nearly the same (but not exact match) as the above specified parameters.
When I use voltage source = 400V (with everything else remaining the same) there is a huge drop in the measured P & Q values and I am unable to follow why is this happening?
Q1) Why are the measured P&Q so low for V = 400V vs V = 2300V? Is there some limitation on the power this grid can deliver? If yes, then how is this being limited and how can I determine what is the maximum power rating of the load that can be connected across this grid source?
Q2) Additionally in the first scenario with 2300V why are the measured P&Q not the exact match of rated power of loads slightly lesser. I assume some power is lost in "losses" but I canot figure out where are these losses happening? Hi Community,
I have modelled a grid using a programmable three phase voltage source and there are three loads attached to it. Model & Parameter file is attached. Each load is defined by the rated active and reactive powers (P& Q) as follows –
Load 1: Rated P = 25 kW; Rated Q = 5 kVA
Load 2: Rated P = 30 kW; rated Q = 10 kVA
Load 3: Rated P = 125 kW; rated Q = 10 kVA
The loads 2 and 3 are switched off at T = 2 secs and switched back on at T = 4 secs. I am also measuring the powers at each of the individual loads as well as the total power supplied by grid.
When I use the voltage source rating = 2300V, the P & Q values are nearly the same (but not exact match) as the above specified parameters.
When I use voltage source = 400V (with everything else remaining the same) there is a huge drop in the measured P & Q values and I am unable to follow why is this happening?
Q1) Why are the measured P&Q so low for V = 400V vs V = 2300V? Is there some limitation on the power this grid can deliver? If yes, then how is this being limited and how can I determine what is the maximum power rating of the load that can be connected across this grid source?
Q2) Additionally in the first scenario with 2300V why are the measured P&Q not the exact match of rated power of loads slightly lesser. I assume some power is lost in "losses" but I canot figure out where are these losses happening? grid, programmable voltage source, active power, reactive power, impedance, power measurement MATLAB Answers — New Questions
How do I extract images from a docx (word) file?
I am trying to extract images for processing from a docx (Word) file. How do I do this?I am trying to extract images for processing from a docx (Word) file. How do I do this? I am trying to extract images for processing from a docx (Word) file. How do I do this? docx, ms word, images MATLAB Answers — New Questions
Question about hair removal matlab code.
Hello all! I am doing a program about hair removal. And I found a code online but part of this code I couln’t understand. The final part(the loop part) was really confused me.
img_b is a binary image and after dilation we could get the img_b binary image, which the black part is skin and the white part is hair. Thus, the ‘for’ part in the final loop is to decide if this pixel is skin or hair, if the pixel is in the skin part then it keeps the same pixel value as the original image; if the pixel is in the hair part, then do ‘else’ and calculate it for removing hair.
So here comes the question, I do not understand the calculation part in ‘else’ and the meaning of parameter r.When I change the value of r into a bigger one, the running speed gets slower. So I wonder could anyone give me a guide about this part please?when I change the value of r into a bigger one, the running speed gets slower. Thank you!
Images are listed below: the first image is which we need to deal with and the second image is the processed image.
Updated on Mar. 7th 2019: Sorry guys forgot to put the otsu function. Already put it in case anyone need it.
if true
clear;
clc;
r=7;
se1_para = 3;
se2_para = 2;
img_old = imread(‘D:MATLAB1binpicsam3-2.jpg’);
figure(1),imshow(img_old);
[x,y,z] = size(img_old);
img = rgb2gray(img_old);
se1 = strel(‘disk’,se1_para);
img_c = imclose(img,se1)
figure(2), imshow(img_c,[]);
img_fur = double(img_c) – double(img);
figure(3),imshow(img_fur,[]);
[X Y]=meshgrid(1:x);
tt=(X-280).^2+(Y-280).^2<280^2;
thresh = otsu(img_fur(tt),sum(tt(:)));
img_b = (img_fur>thresh);
figure(4),imshow(img_b);
se2 = strel(‘disk’,se2_para);
img_b =imdilate(img_b,se2);
figure(5),imshow(img_b);
img_new = uint8(zeros(x,y,z));
for i = 1:x
for j = 1:y
if img_b(i,j) == false
img_new(i,j,:) = img_old(i,j,:);
else
ttt = img_old(max(1,i-r):min(i+r,x),max(j-r,1):min(j+r,y),:);
no_efficient_pix = cat(3,img_b(max(1,i-r):min(i+r,x),max(j-r,1):min(j+r,y)),not(tt(max(1,i-r):min(i+r,x),max(j-r,1):min(j+r,y))));
no_efficient_pix = any(no_efficient_pix,3);
ttt = ttt.*repmat(uint8(not(no_efficient_pix)),[1,1,3]);
efficient_pix_num = (2*r+1)^2-sum(no_efficient_pix(:));
img_new(i,j,:) = uint8(sum(sum(ttt))./efficient_pix_num);
end
end
end
figure(6),imshow(img_new,[]);
end
function thresh = otsu(data,pix_num)
img_var = zeros(256,1);
for i=1:256
w0 = sum(sum(data<=i-1))./pix_num;
w1 = 1-w0;
u0 = sum(sum(data.*double(data<=i-1)))./(w0*pix_num);
u1 = sum(sum(data.*double(data>i-1)))./(w1*pix_num);
img_var(i) = w0.*w1.*((u0-u1).^2);
end
[~,I] = max(img_var);
thresh = I-1;
endHello all! I am doing a program about hair removal. And I found a code online but part of this code I couln’t understand. The final part(the loop part) was really confused me.
img_b is a binary image and after dilation we could get the img_b binary image, which the black part is skin and the white part is hair. Thus, the ‘for’ part in the final loop is to decide if this pixel is skin or hair, if the pixel is in the skin part then it keeps the same pixel value as the original image; if the pixel is in the hair part, then do ‘else’ and calculate it for removing hair.
So here comes the question, I do not understand the calculation part in ‘else’ and the meaning of parameter r.When I change the value of r into a bigger one, the running speed gets slower. So I wonder could anyone give me a guide about this part please?when I change the value of r into a bigger one, the running speed gets slower. Thank you!
Images are listed below: the first image is which we need to deal with and the second image is the processed image.
Updated on Mar. 7th 2019: Sorry guys forgot to put the otsu function. Already put it in case anyone need it.
if true
clear;
clc;
r=7;
se1_para = 3;
se2_para = 2;
img_old = imread(‘D:MATLAB1binpicsam3-2.jpg’);
figure(1),imshow(img_old);
[x,y,z] = size(img_old);
img = rgb2gray(img_old);
se1 = strel(‘disk’,se1_para);
img_c = imclose(img,se1)
figure(2), imshow(img_c,[]);
img_fur = double(img_c) – double(img);
figure(3),imshow(img_fur,[]);
[X Y]=meshgrid(1:x);
tt=(X-280).^2+(Y-280).^2<280^2;
thresh = otsu(img_fur(tt),sum(tt(:)));
img_b = (img_fur>thresh);
figure(4),imshow(img_b);
se2 = strel(‘disk’,se2_para);
img_b =imdilate(img_b,se2);
figure(5),imshow(img_b);
img_new = uint8(zeros(x,y,z));
for i = 1:x
for j = 1:y
if img_b(i,j) == false
img_new(i,j,:) = img_old(i,j,:);
else
ttt = img_old(max(1,i-r):min(i+r,x),max(j-r,1):min(j+r,y),:);
no_efficient_pix = cat(3,img_b(max(1,i-r):min(i+r,x),max(j-r,1):min(j+r,y)),not(tt(max(1,i-r):min(i+r,x),max(j-r,1):min(j+r,y))));
no_efficient_pix = any(no_efficient_pix,3);
ttt = ttt.*repmat(uint8(not(no_efficient_pix)),[1,1,3]);
efficient_pix_num = (2*r+1)^2-sum(no_efficient_pix(:));
img_new(i,j,:) = uint8(sum(sum(ttt))./efficient_pix_num);
end
end
end
figure(6),imshow(img_new,[]);
end
function thresh = otsu(data,pix_num)
img_var = zeros(256,1);
for i=1:256
w0 = sum(sum(data<=i-1))./pix_num;
w1 = 1-w0;
u0 = sum(sum(data.*double(data<=i-1)))./(w0*pix_num);
u1 = sum(sum(data.*double(data>i-1)))./(w1*pix_num);
img_var(i) = w0.*w1.*((u0-u1).^2);
end
[~,I] = max(img_var);
thresh = I-1;
end Hello all! I am doing a program about hair removal. And I found a code online but part of this code I couln’t understand. The final part(the loop part) was really confused me.
img_b is a binary image and after dilation we could get the img_b binary image, which the black part is skin and the white part is hair. Thus, the ‘for’ part in the final loop is to decide if this pixel is skin or hair, if the pixel is in the skin part then it keeps the same pixel value as the original image; if the pixel is in the hair part, then do ‘else’ and calculate it for removing hair.
So here comes the question, I do not understand the calculation part in ‘else’ and the meaning of parameter r.When I change the value of r into a bigger one, the running speed gets slower. So I wonder could anyone give me a guide about this part please?when I change the value of r into a bigger one, the running speed gets slower. Thank you!
Images are listed below: the first image is which we need to deal with and the second image is the processed image.
Updated on Mar. 7th 2019: Sorry guys forgot to put the otsu function. Already put it in case anyone need it.
if true
clear;
clc;
r=7;
se1_para = 3;
se2_para = 2;
img_old = imread(‘D:MATLAB1binpicsam3-2.jpg’);
figure(1),imshow(img_old);
[x,y,z] = size(img_old);
img = rgb2gray(img_old);
se1 = strel(‘disk’,se1_para);
img_c = imclose(img,se1)
figure(2), imshow(img_c,[]);
img_fur = double(img_c) – double(img);
figure(3),imshow(img_fur,[]);
[X Y]=meshgrid(1:x);
tt=(X-280).^2+(Y-280).^2<280^2;
thresh = otsu(img_fur(tt),sum(tt(:)));
img_b = (img_fur>thresh);
figure(4),imshow(img_b);
se2 = strel(‘disk’,se2_para);
img_b =imdilate(img_b,se2);
figure(5),imshow(img_b);
img_new = uint8(zeros(x,y,z));
for i = 1:x
for j = 1:y
if img_b(i,j) == false
img_new(i,j,:) = img_old(i,j,:);
else
ttt = img_old(max(1,i-r):min(i+r,x),max(j-r,1):min(j+r,y),:);
no_efficient_pix = cat(3,img_b(max(1,i-r):min(i+r,x),max(j-r,1):min(j+r,y)),not(tt(max(1,i-r):min(i+r,x),max(j-r,1):min(j+r,y))));
no_efficient_pix = any(no_efficient_pix,3);
ttt = ttt.*repmat(uint8(not(no_efficient_pix)),[1,1,3]);
efficient_pix_num = (2*r+1)^2-sum(no_efficient_pix(:));
img_new(i,j,:) = uint8(sum(sum(ttt))./efficient_pix_num);
end
end
end
figure(6),imshow(img_new,[]);
end
function thresh = otsu(data,pix_num)
img_var = zeros(256,1);
for i=1:256
w0 = sum(sum(data<=i-1))./pix_num;
w1 = 1-w0;
u0 = sum(sum(data.*double(data<=i-1)))./(w0*pix_num);
u1 = sum(sum(data.*double(data>i-1)))./(w1*pix_num);
img_var(i) = w0.*w1.*((u0-u1).^2);
end
[~,I] = max(img_var);
thresh = I-1;
end hair removal MATLAB Answers — New Questions
Entering the mechanical and volumetric efficiency of a fixed displacement pump
I want to enter the mechanical and volumetric efficiency values of a fixed displacement pump in a hydraulic system within SIMScape MATLAB. I have activated the mechanical and volumetric efficiency ports from the pump’s mass variables, but I have not found a way to enter the efficiency values into those ports… I need help to adjust the efficiency values for the pumpI want to enter the mechanical and volumetric efficiency values of a fixed displacement pump in a hydraulic system within SIMScape MATLAB. I have activated the mechanical and volumetric efficiency ports from the pump’s mass variables, but I have not found a way to enter the efficiency values into those ports… I need help to adjust the efficiency values for the pump I want to enter the mechanical and volumetric efficiency values of a fixed displacement pump in a hydraulic system within SIMScape MATLAB. I have activated the mechanical and volumetric efficiency ports from the pump’s mass variables, but I have not found a way to enter the efficiency values into those ports… I need help to adjust the efficiency values for the pump efficiency control MATLAB Answers — New Questions
CRS mismatch or I do not know
I am working onI am working on I am working on notag MATLAB Answers — New Questions
Error evaluating parameter ‘Mass’ , Unable to resolve the name smiData.Solid.
I am getting error when i am, importing assembly from the invent. I am having error at the joints and also the parts imported doesn’t import data regarding inertia or geometry. When i run the simulation, I am getting this error
Caused by:
Error evaluating parameter ‘Mass’ in
Unable to resolve the name smiData.Solid.
Error evaluating parameter ‘CenterOfMass’ in ‘NewTestAssembly
Thank you
Sorry i have to hide few names due to some technical issueI am getting error when i am, importing assembly from the invent. I am having error at the joints and also the parts imported doesn’t import data regarding inertia or geometry. When i run the simulation, I am getting this error
Caused by:
Error evaluating parameter ‘Mass’ in
Unable to resolve the name smiData.Solid.
Error evaluating parameter ‘CenterOfMass’ in ‘NewTestAssembly
Thank you
Sorry i have to hide few names due to some technical issue I am getting error when i am, importing assembly from the invent. I am having error at the joints and also the parts imported doesn’t import data regarding inertia or geometry. When i run the simulation, I am getting this error
Caused by:
Error evaluating parameter ‘Mass’ in
Unable to resolve the name smiData.Solid.
Error evaluating parameter ‘CenterOfMass’ in ‘NewTestAssembly
Thank you
Sorry i have to hide few names due to some technical issue error evaluating, mass MATLAB Answers — New Questions
error when using segment function
I get these errors when running this snippet of code that references another script (script attached as a matlab file)
[filt_in, data_in_segs_corrected, segment_params]=segment_filt_v2(data_to_segment,[],[],params.genome_build);
params.segment_params=segment_params;
Warning: The data contains more columns (number of channels) than rows (number of samples). Check that the data is not transposed inadvertently.
> In ctrlMsgUtils.warning (line 25)
In segment (line 76)
In segment_filt_v2>seg_fun (line 145)
In segment_filt_v2 (line 101)
Unrecognized function or variable ‘jmax’.
Error in segment (line 236)
hh=hist(:,jmax);
Error in segment_filt_v2>seg_fun (line 145)
thm=segment([data_in(idx+1:end),ones(length(data_in)-idx,1)],[0 1 1],R2);
Error in segment_filt_v2 (line 101)
data_in_segs_corrected{Chr}(in,c-4)=seg_fun(Data{Chr}(in,c), R2);I get these errors when running this snippet of code that references another script (script attached as a matlab file)
[filt_in, data_in_segs_corrected, segment_params]=segment_filt_v2(data_to_segment,[],[],params.genome_build);
params.segment_params=segment_params;
Warning: The data contains more columns (number of channels) than rows (number of samples). Check that the data is not transposed inadvertently.
> In ctrlMsgUtils.warning (line 25)
In segment (line 76)
In segment_filt_v2>seg_fun (line 145)
In segment_filt_v2 (line 101)
Unrecognized function or variable ‘jmax’.
Error in segment (line 236)
hh=hist(:,jmax);
Error in segment_filt_v2>seg_fun (line 145)
thm=segment([data_in(idx+1:end),ones(length(data_in)-idx,1)],[0 1 1],R2);
Error in segment_filt_v2 (line 101)
data_in_segs_corrected{Chr}(in,c-4)=seg_fun(Data{Chr}(in,c), R2); I get these errors when running this snippet of code that references another script (script attached as a matlab file)
[filt_in, data_in_segs_corrected, segment_params]=segment_filt_v2(data_to_segment,[],[],params.genome_build);
params.segment_params=segment_params;
Warning: The data contains more columns (number of channels) than rows (number of samples). Check that the data is not transposed inadvertently.
> In ctrlMsgUtils.warning (line 25)
In segment (line 76)
In segment_filt_v2>seg_fun (line 145)
In segment_filt_v2 (line 101)
Unrecognized function or variable ‘jmax’.
Error in segment (line 236)
hh=hist(:,jmax);
Error in segment_filt_v2>seg_fun (line 145)
thm=segment([data_in(idx+1:end),ones(length(data_in)-idx,1)],[0 1 1],R2);
Error in segment_filt_v2 (line 101)
data_in_segs_corrected{Chr}(in,c-4)=seg_fun(Data{Chr}(in,c), R2); segment MATLAB Answers — New Questions