Category: News
Problem with Russian letters in comments
When I write Russian comments in Matlab starting with the “%” symbol, then after the next entry into Matlab, in the place of Russian letters, there are question marks “?”. How to solve this problem?When I write Russian comments in Matlab starting with the “%” symbol, then after the next entry into Matlab, in the place of Russian letters, there are question marks “?”. How to solve this problem? When I write Russian comments in Matlab starting with the “%” symbol, then after the next entry into Matlab, in the place of Russian letters, there are question marks “?”. How to solve this problem? russian letters MATLAB Answers — New Questions
calculate mean of 4D array
I have 41 years monthly data of temperature (lat,lon,depth,time,temperature). I wanted to calculate annual mean and seasonal mean [(summer: Dec, Jan, Feb), (autumn: Mar, Apr, May), (winter = Jun, Jul, Aug), (spring = Sep, Oct, Nov)] of each grid, eache depth level for the period of 1982-2022.I have 41 years monthly data of temperature (lat,lon,depth,time,temperature). I wanted to calculate annual mean and seasonal mean [(summer: Dec, Jan, Feb), (autumn: Mar, Apr, May), (winter = Jun, Jul, Aug), (spring = Sep, Oct, Nov)] of each grid, eache depth level for the period of 1982-2022. I have 41 years monthly data of temperature (lat,lon,depth,time,temperature). I wanted to calculate annual mean and seasonal mean [(summer: Dec, Jan, Feb), (autumn: Mar, Apr, May), (winter = Jun, Jul, Aug), (spring = Sep, Oct, Nov)] of each grid, eache depth level for the period of 1982-2022. mean, ts_downsamples, matlab, statistics MATLAB Answers — New Questions
How do I plot a polynomial equation and set of x-y coordinates on the same graph?
I am trying to plot a polynmial and some x-y coordinates on the same graph. I need the coordinates to be visible and the lines to be distingushable from one another (eg. different colors).
Here is the measured data.
coefficients = [0.6252 -0.4165 0.1311 -0.0163 0.0009,-0.0000]
x = [2 5 8 11 14 20];
y = [0.20 0.29 0.44 0.50 0.66 0.56];I am trying to plot a polynmial and some x-y coordinates on the same graph. I need the coordinates to be visible and the lines to be distingushable from one another (eg. different colors).
Here is the measured data.
coefficients = [0.6252 -0.4165 0.1311 -0.0163 0.0009,-0.0000]
x = [2 5 8 11 14 20];
y = [0.20 0.29 0.44 0.50 0.66 0.56]; I am trying to plot a polynmial and some x-y coordinates on the same graph. I need the coordinates to be visible and the lines to be distingushable from one another (eg. different colors).
Here is the measured data.
coefficients = [0.6252 -0.4165 0.1311 -0.0163 0.0009,-0.0000]
x = [2 5 8 11 14 20];
y = [0.20 0.29 0.44 0.50 0.66 0.56]; interpolation, graph, data MATLAB Answers — New Questions
Where to start IoT?
I’m aware how IoT basics works, but I really want to go into depths of it, from scratch, where should I begin? I cannot afford any courses, and also, someone is willing to teach?
I’m aware how IoT basics works, but I really want to go into depths of it, from scratch, where should I begin? I cannot afford any courses, and also, someone is willing to teach? Read More
Esaver Watt Reviews 2024-{SPECIAL PROMO FOR 2024}-Hurry make it your order with Esaver Watt Official
Discover the Power of Esaver Watt Energy Saving Device
In today’s fast-paced world, where technology plays a significant role in our lives, energy consumption has skyrocketed. From our homes to our offices, we are constantly on the lookout for ways to reduce our energy bills while being environmentally friendly. This is where Esaver Watt comes into the picture. If you’re tired of hefty electricity bills and want to make a positive impact on the environment, then it is time to discover the power of Esaver Watt energy-saving device.
Today’s Special Offer – Esaver Watt Official Website – Get 70% Off And Free Shipping!
Discover the Power of Esaver Watt Energy Saving DeviceIn today’s fast-paced world, where technology plays a significant role in our lives, energy consumption has skyrocketed. From our homes to our offices, we are constantly on the lookout for ways to reduce our energy bills while being environmentally friendly. This is where Esaver Watt comes into the picture. If you’re tired of hefty electricity bills and want to make a positive impact on the environment, then it is time to discover the power of Esaver Watt energy-saving device. Today’s Special Offer – Esaver Watt Official Website – Get 70% Off And Free Shipping! Read More
deleted cells causing REF
Can anyone help me fix my worksheet? I deleted a cell or it got moved and now I have a #REF! error and I can not undo it.
Can anyone help me fix my worksheet? I deleted a cell or it got moved and now I have a #REF! error and I can not undo it. Read More
Add an additional condition where the value is greater than 0
Hi folks,
The following formula is used to return the number of times a week number is found in Sheet1
=COUNTIF(Sheet1!$R$5:$R$1000,D24)
Now I only want the number of times the week number is found to only return a result if the value(s) in colO has a value greater than (0)
The range to include in the formula:
Sheet1!$O$5:$O$1000
To give you a better idea what I am looking to do here is my (poor) attempt to include the condition in the original formula:
=COUNTIF((Sheet1!$R$5:$R$1000,D24),Sheet1!$O$5:$O$1000, >0))
Thank you for taking a look!
Hi folks, The following formula is used to return the number of times a week number is found in Sheet1=COUNTIF(Sheet1!$R$5:$R$1000,D24) Now I only want the number of times the week number is found to only return a result if the value(s) in colO has a value greater than (0)The range to include in the formula:Sheet1!$O$5:$O$1000 To give you a better idea what I am looking to do here is my (poor) attempt to include the condition in the original formula: =COUNTIF((Sheet1!$R$5:$R$1000,D24),Sheet1!$O$5:$O$1000, >0)) Thank you for taking a look! Read More
Struggling to train a DDPG agent – 3DOF aircraft control
Hello everyone,
As in the title, I am struggling to train a DDPG agent to behave like a TECS (Total Energy Control System) Algorithm. The idea is the following; I have my 3DOF airframe model + the innerloops that control the commanded pitch angle and the commanded thrust. These two commands must come from the RL agent so that the airframe will keep the same altitude while gaining airspeed.
The observations are:
The reference airspeed and altitude at three different instants of time;
The error signals between the airspeed/altitude and the references.
In order to build the reward functions, I have exploited the generateRewardFunction as suggested here in the example of the water tank. In particular, I have generated two Model Verification Blocks:
– Check Step Response Charateristics for the airspeed; I’d like to reach a setpoint 2 m/s higher with respect to the trim one with a given transient
this is the generated reward function
function spd_reward = SpdTrackRewardFunction(V_out,t, V0)
% REWARDFUNCTION generates rewards from Simulink block specifications.
%
% V_out : Input of RL_Training_TECS_Model/Check Airspeed Response Characteristics
% t : Simulation time (s)
% Reinforcement Learning Toolbox
% 07-May-2024 12:19:41
%#codegen
%% Specifications from RL_Training_TECS_Model/Check Airspeed Response Characteristics
Block1_x = V_out;
Block1_InitialValue = V0;
Block1_FinalValue = V0+2;
Block1_StepTime = 0;
Block1_StepRange = Block1_FinalValue – …
Block1_InitialValue;
Block1_MinRise = Block1_InitialValue + …
Block1_StepRange * 80/100;
Block1_MaxSettling = Block1_InitialValue + …
Block1_StepRange * (1+1/100);
Block1_MinSettling = Block1_InitialValue + …
Block1_StepRange * (1-1/100);
Block1_MaxOvershoot = Block1_InitialValue + …
Block1_StepRange * (1+2/100);
Block1_MinUndershoot = Block1_InitialValue – …
Block1_StepRange * 1/100;
if t >= Block1_StepTime
if Block1_InitialValue <= Block1_FinalValue
Block1_UpperBoundTimes = [0,100; 100,max(100+1,t+1)];
Block1_UpperBoundAmplitudes = [ …
Block1_MaxOvershoot,Block1_MaxOvershoot; …
Block1_MaxSettling,Block1_MaxSettling];
Block1_LowerBoundTimes = [0,60; 60,100; 100,max(100+1,t+1)];
Block1_LowerBoundAmplitudes = [ …
Block1_MinUndershoot,Block1_MinUndershoot; …
Block1_MinRise,Block1_MinRise; …
Block1_MinSettling,Block1_MinSettling];
else
Block1_UpperBoundTimes = [0,60; 60,100; 100,max(100+1,t+1)];
Block1_UpperBoundAmplitudes = [ …
Block1_MinUndershoot,Block1_MinUndershoot; …
Block1_MinRise,Block1_MinRise; …
Block1_MinSettling,Block1_MinSettling];
Block1_LowerBoundTimes = [0,100; 100,max(100+1,t+1)];
Block1_LowerBoundAmplitudes = [ …
Block1_MaxOvershoot,Block1_MaxOvershoot; …
Block1_MaxSettling,Block1_MaxSettling];
end
Block1_xmax = zeros(1,size(Block1_UpperBoundTimes,1));
for idx = 1:numel(Block1_xmax)
tseg = Block1_UpperBoundTimes(idx,:);
xseg = Block1_UpperBoundAmplitudes(idx,:);
Block1_xmax(idx) = interp1(tseg,xseg,t,’linear’,NaN);
end
if all(isnan(Block1_xmax))
Block1_xmax = Inf;
else
Block1_xmax = max(Block1_xmax,[],’omitnan’);
end
Block1_xmin = zeros(1,size(Block1_LowerBoundTimes,1));
for idx = 1:numel(Block1_xmin)
tseg = Block1_LowerBoundTimes(idx,:);
xseg = Block1_LowerBoundAmplitudes(idx,:);
Block1_xmin(idx) = interp1(tseg,xseg,t,’linear’,NaN);
end
if all(isnan(Block1_xmin))
Block1_xmin = -Inf;
else
Block1_xmin = max(Block1_xmin,[],’omitnan’);
end
else
Block1_xmin = -Inf;
Block1_xmax = Inf;
end
%% Penalty function weight (specify nonnegative)
Weight = 1;
%% Compute penalty
% Penalty is computed for violation of linear bound constraints.
%
% Use the following functions to compute penalties on constraints.
% – exteriorPenalty
% – barrierPenalty
% – hyperbolicPenalty
% For exteriorPenalty,
% Specify the penalty method as step or quadratic.
%
% For more information, see help for these functions.
Penalty = sum(exteriorPenalty(Block1_x, Block1_xmin, Block1_xmax, ‘step’));
%% Compute reward
spd_reward = – Weight * Penalty;
end
– Check custom bounds for the altitude, in order to generate a "safe box" +/- 1.6 m wide with respect to the trim altitude
the following is the generated reward function
function alt_reward = AltBoundsRewardFunction(Alt_out,t, Alt_hold, t_fin)
% REWARDFUNCTION generates rewards from Simulink block specifications.
%
% Alt_out : Input of RL_Training_TECS_Model/Check Altitude Bounds
% t : Simulation time (s)
% Reinforcement Learning Toolbox
% 07-May-2024 14:07:07
%#codegen
%% Specifications from RL_Training_TECS_Model/Check Altitude Bounds
Block1_x = Alt_out;
Block1_UpperBoundTimes = [0 t_fin];
Block1_UpperBoundAmplitudes = [Alt_hold+1.6 Alt_hold+1.6];
Block1_xmax = zeros(1,size(Block1_UpperBoundTimes,1));
for idx = 1:numel(Block1_xmax)
tseg = Block1_UpperBoundTimes(idx,:);
xseg = Block1_UpperBoundAmplitudes(idx,:);
Block1_xmax(idx) = interp1(tseg,xseg,t,’linear’,NaN);
end
if all(isnan(Block1_xmax))
Block1_xmax = Inf;
else
Block1_xmax = max(Block1_xmax,[],’omitnan’);
end
Block1_LowerBoundTimes = [0 t_fin];
Block1_LowerBoundAmplitudes = [Alt_hold-1.6 Alt_hold-1.6];
Block1_xmin = zeros(1,size(Block1_LowerBoundTimes,1));
for idx = 1:numel(Block1_xmin)
tseg = Block1_LowerBoundTimes(idx,:);
xseg = Block1_LowerBoundAmplitudes(idx,:);
Block1_xmin(idx) = interp1(tseg,xseg,t,’linear’,NaN);
end
if all(isnan(Block1_xmin))
Block1_xmin = -Inf;
else
Block1_xmin = max(Block1_xmin,[],’omitnan’);
end
%% Penalty function weight (specify nonnegative)
Weight = 1;
%% Compute penalty
% Penalty is computed for violation of linear bound constraints.
%
% Use the following functions to compute penalties on constraints.
% – exteriorPenalty
% – barrierPenalty
% – hyperbolicPenalty
% For exteriorPenalty,
% Specify the penalty method as step or quadratic.
%
% For more information, see help for these functions.
Penalty = sum(exteriorPenalty(Block1_x, Block1_xmin, Block1_xmax, ‘step’));
%% Compute reward
alt_reward = – Weight * Penalty;
end
In addition to these two rewards, I have also considered two penalty functions when the commanded actions are too close to the saturation boundaries. Indeed, as you can see from the picture of the model, the two actions must be within a maximum and a minimum value. In particoular, the minimum action for both the pitch and the thrust is a constant value while the maximum depends for both the actions on the airspeed and alitude pair, so it is a dynamic bound.
function PitchPenalty = PitchCmdPenalty(u, u_max, u_min)
k_PP = -100;
u_center = (u_max + u_min)/2;
PitchPenalty = k_PP*(u – u_center)^2;
end
function ThrustPenalty = ThrustCmdPenalty(u, u_max, u_min)
k_TP = -1e-7;
u_center = (u_max + u_min)/2;
ThrustPenalty = k_TP*(u – u_center)^2;
end
The two weights here are selected so that the penalty is more or less the same for both the actions, as you can see.
The isdone command is generated so that when the airspeed/altitude is outside the boundaries for more than x seconds, the episode will stop.
The random function that initialize the episodes will generate a random trim condition within a given "reference box" in the envelope of the aircraft.
The agent options are the following
% Build and configure the DDPG object
ddpg_opt = rlDDPGAgentOptions; % option constructor
ddpg_opt.SampleTime = 0.1;
ddpg_opt.NoiseOptions.StandardDeviation = [0.1; 0.1];
ddpg_opt.NoiseOptions.StandardDeviationDecayRate = 1e-6;
ddpg_opt.NoiseOptions.Variance = 0.015;
ddpg_opt.NoiseOptions.VarianceDecayRate = 1e-6;
ddpg_opt.ExperienceBufferLength = 1e6;
ddpg_opt.MiniBatchSize = 256;
AltHoldTECSAgent = rlDDPGAgent(obsInfo, actInfo, ddpg_opt)
% get the actor
actor = getActor(AltHoldTECSAgent);
actorNet = getModel(actor);
actorLayers = actorNet.Layers;
% configure the learning
learnOptions = rlOptimizerOptions("LearnRate",1e-03,"GradientThreshold",1);
actor.UseDevice = ‘cpu’;
ddpg_opt.ActorOptimizerOptions = learnOptions;
% get the critic
critic = getCritic(AltHoldTECSAgent);
criticNet = getModel(critic);
criticLayers = criticNet.Layers;
% configure the critic
critic.UseDevice = ‘gpu’;
ddpg_opt.CriticOptimizerOptions = learnOptions;
AltHoldTECSAgent = rlDDPGAgent(actor, critic, ddpg_opt);
trainOptions = rlTrainingOptions();
trainOptions.MaxEpisodes = 1200;
trainOptions.MaxStepsPerEpisode = 150;
trainOptions.StopTrainingCriteria = "AverageReward";
trainOptions.StopTrainingValue = 0;
trainOptions.ScoreAveragingWindowLength = 5;
trainStats = train(AltHoldTECSAgent, rlEnv, trainOptions);
I’ve started several trainings, but I have stopped them because everytime the ‘Episode Q0’ diverges and the commaned actions are always in the order of 10^6 radiants for the pitch and 10^7 Newton for the thrust…
Do you have any suggestions in order to improve the training? Or some others realted example?
Thank you.Hello everyone,
As in the title, I am struggling to train a DDPG agent to behave like a TECS (Total Energy Control System) Algorithm. The idea is the following; I have my 3DOF airframe model + the innerloops that control the commanded pitch angle and the commanded thrust. These two commands must come from the RL agent so that the airframe will keep the same altitude while gaining airspeed.
The observations are:
The reference airspeed and altitude at three different instants of time;
The error signals between the airspeed/altitude and the references.
In order to build the reward functions, I have exploited the generateRewardFunction as suggested here in the example of the water tank. In particular, I have generated two Model Verification Blocks:
– Check Step Response Charateristics for the airspeed; I’d like to reach a setpoint 2 m/s higher with respect to the trim one with a given transient
this is the generated reward function
function spd_reward = SpdTrackRewardFunction(V_out,t, V0)
% REWARDFUNCTION generates rewards from Simulink block specifications.
%
% V_out : Input of RL_Training_TECS_Model/Check Airspeed Response Characteristics
% t : Simulation time (s)
% Reinforcement Learning Toolbox
% 07-May-2024 12:19:41
%#codegen
%% Specifications from RL_Training_TECS_Model/Check Airspeed Response Characteristics
Block1_x = V_out;
Block1_InitialValue = V0;
Block1_FinalValue = V0+2;
Block1_StepTime = 0;
Block1_StepRange = Block1_FinalValue – …
Block1_InitialValue;
Block1_MinRise = Block1_InitialValue + …
Block1_StepRange * 80/100;
Block1_MaxSettling = Block1_InitialValue + …
Block1_StepRange * (1+1/100);
Block1_MinSettling = Block1_InitialValue + …
Block1_StepRange * (1-1/100);
Block1_MaxOvershoot = Block1_InitialValue + …
Block1_StepRange * (1+2/100);
Block1_MinUndershoot = Block1_InitialValue – …
Block1_StepRange * 1/100;
if t >= Block1_StepTime
if Block1_InitialValue <= Block1_FinalValue
Block1_UpperBoundTimes = [0,100; 100,max(100+1,t+1)];
Block1_UpperBoundAmplitudes = [ …
Block1_MaxOvershoot,Block1_MaxOvershoot; …
Block1_MaxSettling,Block1_MaxSettling];
Block1_LowerBoundTimes = [0,60; 60,100; 100,max(100+1,t+1)];
Block1_LowerBoundAmplitudes = [ …
Block1_MinUndershoot,Block1_MinUndershoot; …
Block1_MinRise,Block1_MinRise; …
Block1_MinSettling,Block1_MinSettling];
else
Block1_UpperBoundTimes = [0,60; 60,100; 100,max(100+1,t+1)];
Block1_UpperBoundAmplitudes = [ …
Block1_MinUndershoot,Block1_MinUndershoot; …
Block1_MinRise,Block1_MinRise; …
Block1_MinSettling,Block1_MinSettling];
Block1_LowerBoundTimes = [0,100; 100,max(100+1,t+1)];
Block1_LowerBoundAmplitudes = [ …
Block1_MaxOvershoot,Block1_MaxOvershoot; …
Block1_MaxSettling,Block1_MaxSettling];
end
Block1_xmax = zeros(1,size(Block1_UpperBoundTimes,1));
for idx = 1:numel(Block1_xmax)
tseg = Block1_UpperBoundTimes(idx,:);
xseg = Block1_UpperBoundAmplitudes(idx,:);
Block1_xmax(idx) = interp1(tseg,xseg,t,’linear’,NaN);
end
if all(isnan(Block1_xmax))
Block1_xmax = Inf;
else
Block1_xmax = max(Block1_xmax,[],’omitnan’);
end
Block1_xmin = zeros(1,size(Block1_LowerBoundTimes,1));
for idx = 1:numel(Block1_xmin)
tseg = Block1_LowerBoundTimes(idx,:);
xseg = Block1_LowerBoundAmplitudes(idx,:);
Block1_xmin(idx) = interp1(tseg,xseg,t,’linear’,NaN);
end
if all(isnan(Block1_xmin))
Block1_xmin = -Inf;
else
Block1_xmin = max(Block1_xmin,[],’omitnan’);
end
else
Block1_xmin = -Inf;
Block1_xmax = Inf;
end
%% Penalty function weight (specify nonnegative)
Weight = 1;
%% Compute penalty
% Penalty is computed for violation of linear bound constraints.
%
% Use the following functions to compute penalties on constraints.
% – exteriorPenalty
% – barrierPenalty
% – hyperbolicPenalty
% For exteriorPenalty,
% Specify the penalty method as step or quadratic.
%
% For more information, see help for these functions.
Penalty = sum(exteriorPenalty(Block1_x, Block1_xmin, Block1_xmax, ‘step’));
%% Compute reward
spd_reward = – Weight * Penalty;
end
– Check custom bounds for the altitude, in order to generate a "safe box" +/- 1.6 m wide with respect to the trim altitude
the following is the generated reward function
function alt_reward = AltBoundsRewardFunction(Alt_out,t, Alt_hold, t_fin)
% REWARDFUNCTION generates rewards from Simulink block specifications.
%
% Alt_out : Input of RL_Training_TECS_Model/Check Altitude Bounds
% t : Simulation time (s)
% Reinforcement Learning Toolbox
% 07-May-2024 14:07:07
%#codegen
%% Specifications from RL_Training_TECS_Model/Check Altitude Bounds
Block1_x = Alt_out;
Block1_UpperBoundTimes = [0 t_fin];
Block1_UpperBoundAmplitudes = [Alt_hold+1.6 Alt_hold+1.6];
Block1_xmax = zeros(1,size(Block1_UpperBoundTimes,1));
for idx = 1:numel(Block1_xmax)
tseg = Block1_UpperBoundTimes(idx,:);
xseg = Block1_UpperBoundAmplitudes(idx,:);
Block1_xmax(idx) = interp1(tseg,xseg,t,’linear’,NaN);
end
if all(isnan(Block1_xmax))
Block1_xmax = Inf;
else
Block1_xmax = max(Block1_xmax,[],’omitnan’);
end
Block1_LowerBoundTimes = [0 t_fin];
Block1_LowerBoundAmplitudes = [Alt_hold-1.6 Alt_hold-1.6];
Block1_xmin = zeros(1,size(Block1_LowerBoundTimes,1));
for idx = 1:numel(Block1_xmin)
tseg = Block1_LowerBoundTimes(idx,:);
xseg = Block1_LowerBoundAmplitudes(idx,:);
Block1_xmin(idx) = interp1(tseg,xseg,t,’linear’,NaN);
end
if all(isnan(Block1_xmin))
Block1_xmin = -Inf;
else
Block1_xmin = max(Block1_xmin,[],’omitnan’);
end
%% Penalty function weight (specify nonnegative)
Weight = 1;
%% Compute penalty
% Penalty is computed for violation of linear bound constraints.
%
% Use the following functions to compute penalties on constraints.
% – exteriorPenalty
% – barrierPenalty
% – hyperbolicPenalty
% For exteriorPenalty,
% Specify the penalty method as step or quadratic.
%
% For more information, see help for these functions.
Penalty = sum(exteriorPenalty(Block1_x, Block1_xmin, Block1_xmax, ‘step’));
%% Compute reward
alt_reward = – Weight * Penalty;
end
In addition to these two rewards, I have also considered two penalty functions when the commanded actions are too close to the saturation boundaries. Indeed, as you can see from the picture of the model, the two actions must be within a maximum and a minimum value. In particoular, the minimum action for both the pitch and the thrust is a constant value while the maximum depends for both the actions on the airspeed and alitude pair, so it is a dynamic bound.
function PitchPenalty = PitchCmdPenalty(u, u_max, u_min)
k_PP = -100;
u_center = (u_max + u_min)/2;
PitchPenalty = k_PP*(u – u_center)^2;
end
function ThrustPenalty = ThrustCmdPenalty(u, u_max, u_min)
k_TP = -1e-7;
u_center = (u_max + u_min)/2;
ThrustPenalty = k_TP*(u – u_center)^2;
end
The two weights here are selected so that the penalty is more or less the same for both the actions, as you can see.
The isdone command is generated so that when the airspeed/altitude is outside the boundaries for more than x seconds, the episode will stop.
The random function that initialize the episodes will generate a random trim condition within a given "reference box" in the envelope of the aircraft.
The agent options are the following
% Build and configure the DDPG object
ddpg_opt = rlDDPGAgentOptions; % option constructor
ddpg_opt.SampleTime = 0.1;
ddpg_opt.NoiseOptions.StandardDeviation = [0.1; 0.1];
ddpg_opt.NoiseOptions.StandardDeviationDecayRate = 1e-6;
ddpg_opt.NoiseOptions.Variance = 0.015;
ddpg_opt.NoiseOptions.VarianceDecayRate = 1e-6;
ddpg_opt.ExperienceBufferLength = 1e6;
ddpg_opt.MiniBatchSize = 256;
AltHoldTECSAgent = rlDDPGAgent(obsInfo, actInfo, ddpg_opt)
% get the actor
actor = getActor(AltHoldTECSAgent);
actorNet = getModel(actor);
actorLayers = actorNet.Layers;
% configure the learning
learnOptions = rlOptimizerOptions("LearnRate",1e-03,"GradientThreshold",1);
actor.UseDevice = ‘cpu’;
ddpg_opt.ActorOptimizerOptions = learnOptions;
% get the critic
critic = getCritic(AltHoldTECSAgent);
criticNet = getModel(critic);
criticLayers = criticNet.Layers;
% configure the critic
critic.UseDevice = ‘gpu’;
ddpg_opt.CriticOptimizerOptions = learnOptions;
AltHoldTECSAgent = rlDDPGAgent(actor, critic, ddpg_opt);
trainOptions = rlTrainingOptions();
trainOptions.MaxEpisodes = 1200;
trainOptions.MaxStepsPerEpisode = 150;
trainOptions.StopTrainingCriteria = "AverageReward";
trainOptions.StopTrainingValue = 0;
trainOptions.ScoreAveragingWindowLength = 5;
trainStats = train(AltHoldTECSAgent, rlEnv, trainOptions);
I’ve started several trainings, but I have stopped them because everytime the ‘Episode Q0’ diverges and the commaned actions are always in the order of 10^6 radiants for the pitch and 10^7 Newton for the thrust…
Do you have any suggestions in order to improve the training? Or some others realted example?
Thank you. Hello everyone,
As in the title, I am struggling to train a DDPG agent to behave like a TECS (Total Energy Control System) Algorithm. The idea is the following; I have my 3DOF airframe model + the innerloops that control the commanded pitch angle and the commanded thrust. These two commands must come from the RL agent so that the airframe will keep the same altitude while gaining airspeed.
The observations are:
The reference airspeed and altitude at three different instants of time;
The error signals between the airspeed/altitude and the references.
In order to build the reward functions, I have exploited the generateRewardFunction as suggested here in the example of the water tank. In particular, I have generated two Model Verification Blocks:
– Check Step Response Charateristics for the airspeed; I’d like to reach a setpoint 2 m/s higher with respect to the trim one with a given transient
this is the generated reward function
function spd_reward = SpdTrackRewardFunction(V_out,t, V0)
% REWARDFUNCTION generates rewards from Simulink block specifications.
%
% V_out : Input of RL_Training_TECS_Model/Check Airspeed Response Characteristics
% t : Simulation time (s)
% Reinforcement Learning Toolbox
% 07-May-2024 12:19:41
%#codegen
%% Specifications from RL_Training_TECS_Model/Check Airspeed Response Characteristics
Block1_x = V_out;
Block1_InitialValue = V0;
Block1_FinalValue = V0+2;
Block1_StepTime = 0;
Block1_StepRange = Block1_FinalValue – …
Block1_InitialValue;
Block1_MinRise = Block1_InitialValue + …
Block1_StepRange * 80/100;
Block1_MaxSettling = Block1_InitialValue + …
Block1_StepRange * (1+1/100);
Block1_MinSettling = Block1_InitialValue + …
Block1_StepRange * (1-1/100);
Block1_MaxOvershoot = Block1_InitialValue + …
Block1_StepRange * (1+2/100);
Block1_MinUndershoot = Block1_InitialValue – …
Block1_StepRange * 1/100;
if t >= Block1_StepTime
if Block1_InitialValue <= Block1_FinalValue
Block1_UpperBoundTimes = [0,100; 100,max(100+1,t+1)];
Block1_UpperBoundAmplitudes = [ …
Block1_MaxOvershoot,Block1_MaxOvershoot; …
Block1_MaxSettling,Block1_MaxSettling];
Block1_LowerBoundTimes = [0,60; 60,100; 100,max(100+1,t+1)];
Block1_LowerBoundAmplitudes = [ …
Block1_MinUndershoot,Block1_MinUndershoot; …
Block1_MinRise,Block1_MinRise; …
Block1_MinSettling,Block1_MinSettling];
else
Block1_UpperBoundTimes = [0,60; 60,100; 100,max(100+1,t+1)];
Block1_UpperBoundAmplitudes = [ …
Block1_MinUndershoot,Block1_MinUndershoot; …
Block1_MinRise,Block1_MinRise; …
Block1_MinSettling,Block1_MinSettling];
Block1_LowerBoundTimes = [0,100; 100,max(100+1,t+1)];
Block1_LowerBoundAmplitudes = [ …
Block1_MaxOvershoot,Block1_MaxOvershoot; …
Block1_MaxSettling,Block1_MaxSettling];
end
Block1_xmax = zeros(1,size(Block1_UpperBoundTimes,1));
for idx = 1:numel(Block1_xmax)
tseg = Block1_UpperBoundTimes(idx,:);
xseg = Block1_UpperBoundAmplitudes(idx,:);
Block1_xmax(idx) = interp1(tseg,xseg,t,’linear’,NaN);
end
if all(isnan(Block1_xmax))
Block1_xmax = Inf;
else
Block1_xmax = max(Block1_xmax,[],’omitnan’);
end
Block1_xmin = zeros(1,size(Block1_LowerBoundTimes,1));
for idx = 1:numel(Block1_xmin)
tseg = Block1_LowerBoundTimes(idx,:);
xseg = Block1_LowerBoundAmplitudes(idx,:);
Block1_xmin(idx) = interp1(tseg,xseg,t,’linear’,NaN);
end
if all(isnan(Block1_xmin))
Block1_xmin = -Inf;
else
Block1_xmin = max(Block1_xmin,[],’omitnan’);
end
else
Block1_xmin = -Inf;
Block1_xmax = Inf;
end
%% Penalty function weight (specify nonnegative)
Weight = 1;
%% Compute penalty
% Penalty is computed for violation of linear bound constraints.
%
% Use the following functions to compute penalties on constraints.
% – exteriorPenalty
% – barrierPenalty
% – hyperbolicPenalty
% For exteriorPenalty,
% Specify the penalty method as step or quadratic.
%
% For more information, see help for these functions.
Penalty = sum(exteriorPenalty(Block1_x, Block1_xmin, Block1_xmax, ‘step’));
%% Compute reward
spd_reward = – Weight * Penalty;
end
– Check custom bounds for the altitude, in order to generate a "safe box" +/- 1.6 m wide with respect to the trim altitude
the following is the generated reward function
function alt_reward = AltBoundsRewardFunction(Alt_out,t, Alt_hold, t_fin)
% REWARDFUNCTION generates rewards from Simulink block specifications.
%
% Alt_out : Input of RL_Training_TECS_Model/Check Altitude Bounds
% t : Simulation time (s)
% Reinforcement Learning Toolbox
% 07-May-2024 14:07:07
%#codegen
%% Specifications from RL_Training_TECS_Model/Check Altitude Bounds
Block1_x = Alt_out;
Block1_UpperBoundTimes = [0 t_fin];
Block1_UpperBoundAmplitudes = [Alt_hold+1.6 Alt_hold+1.6];
Block1_xmax = zeros(1,size(Block1_UpperBoundTimes,1));
for idx = 1:numel(Block1_xmax)
tseg = Block1_UpperBoundTimes(idx,:);
xseg = Block1_UpperBoundAmplitudes(idx,:);
Block1_xmax(idx) = interp1(tseg,xseg,t,’linear’,NaN);
end
if all(isnan(Block1_xmax))
Block1_xmax = Inf;
else
Block1_xmax = max(Block1_xmax,[],’omitnan’);
end
Block1_LowerBoundTimes = [0 t_fin];
Block1_LowerBoundAmplitudes = [Alt_hold-1.6 Alt_hold-1.6];
Block1_xmin = zeros(1,size(Block1_LowerBoundTimes,1));
for idx = 1:numel(Block1_xmin)
tseg = Block1_LowerBoundTimes(idx,:);
xseg = Block1_LowerBoundAmplitudes(idx,:);
Block1_xmin(idx) = interp1(tseg,xseg,t,’linear’,NaN);
end
if all(isnan(Block1_xmin))
Block1_xmin = -Inf;
else
Block1_xmin = max(Block1_xmin,[],’omitnan’);
end
%% Penalty function weight (specify nonnegative)
Weight = 1;
%% Compute penalty
% Penalty is computed for violation of linear bound constraints.
%
% Use the following functions to compute penalties on constraints.
% – exteriorPenalty
% – barrierPenalty
% – hyperbolicPenalty
% For exteriorPenalty,
% Specify the penalty method as step or quadratic.
%
% For more information, see help for these functions.
Penalty = sum(exteriorPenalty(Block1_x, Block1_xmin, Block1_xmax, ‘step’));
%% Compute reward
alt_reward = – Weight * Penalty;
end
In addition to these two rewards, I have also considered two penalty functions when the commanded actions are too close to the saturation boundaries. Indeed, as you can see from the picture of the model, the two actions must be within a maximum and a minimum value. In particoular, the minimum action for both the pitch and the thrust is a constant value while the maximum depends for both the actions on the airspeed and alitude pair, so it is a dynamic bound.
function PitchPenalty = PitchCmdPenalty(u, u_max, u_min)
k_PP = -100;
u_center = (u_max + u_min)/2;
PitchPenalty = k_PP*(u – u_center)^2;
end
function ThrustPenalty = ThrustCmdPenalty(u, u_max, u_min)
k_TP = -1e-7;
u_center = (u_max + u_min)/2;
ThrustPenalty = k_TP*(u – u_center)^2;
end
The two weights here are selected so that the penalty is more or less the same for both the actions, as you can see.
The isdone command is generated so that when the airspeed/altitude is outside the boundaries for more than x seconds, the episode will stop.
The random function that initialize the episodes will generate a random trim condition within a given "reference box" in the envelope of the aircraft.
The agent options are the following
% Build and configure the DDPG object
ddpg_opt = rlDDPGAgentOptions; % option constructor
ddpg_opt.SampleTime = 0.1;
ddpg_opt.NoiseOptions.StandardDeviation = [0.1; 0.1];
ddpg_opt.NoiseOptions.StandardDeviationDecayRate = 1e-6;
ddpg_opt.NoiseOptions.Variance = 0.015;
ddpg_opt.NoiseOptions.VarianceDecayRate = 1e-6;
ddpg_opt.ExperienceBufferLength = 1e6;
ddpg_opt.MiniBatchSize = 256;
AltHoldTECSAgent = rlDDPGAgent(obsInfo, actInfo, ddpg_opt)
% get the actor
actor = getActor(AltHoldTECSAgent);
actorNet = getModel(actor);
actorLayers = actorNet.Layers;
% configure the learning
learnOptions = rlOptimizerOptions("LearnRate",1e-03,"GradientThreshold",1);
actor.UseDevice = ‘cpu’;
ddpg_opt.ActorOptimizerOptions = learnOptions;
% get the critic
critic = getCritic(AltHoldTECSAgent);
criticNet = getModel(critic);
criticLayers = criticNet.Layers;
% configure the critic
critic.UseDevice = ‘gpu’;
ddpg_opt.CriticOptimizerOptions = learnOptions;
AltHoldTECSAgent = rlDDPGAgent(actor, critic, ddpg_opt);
trainOptions = rlTrainingOptions();
trainOptions.MaxEpisodes = 1200;
trainOptions.MaxStepsPerEpisode = 150;
trainOptions.StopTrainingCriteria = "AverageReward";
trainOptions.StopTrainingValue = 0;
trainOptions.ScoreAveragingWindowLength = 5;
trainStats = train(AltHoldTECSAgent, rlEnv, trainOptions);
I’ve started several trainings, but I have stopped them because everytime the ‘Episode Q0’ diverges and the commaned actions are always in the order of 10^6 radiants for the pitch and 10^7 Newton for the thrust…
Do you have any suggestions in order to improve the training? Or some others realted example?
Thank you. control, deep learning, reinforcement learning, ddpg MATLAB Answers — New Questions
how can I convert a double image into gray unit8 image?
Lets say that we have a 256×256 double image, how can we convert it into a 256×256 uint8?Lets say that we have a 256×256 double image, how can we convert it into a 256×256 uint8? Lets say that we have a 256×256 double image, how can we convert it into a 256×256 uint8? MATLAB Answers — New Questions
My email is as an unverified sender
My email address, which was recently created, is not receiving emails, I did some sending tests and my email address is appearing as a random email address, example: @outlook6789w7262992
I don’t understand why this happens and I would like it to be resolved. Thanks.
My email address, which was recently created, is not receiving emails, I did some sending tests and my email address is appearing as a random email address, example: @outlook6789w7262992I don’t understand why this happens and I would like it to be resolved. Thanks. Read More
How to format list of figures to have left-aligned labels, centered captions, and right aligned pgno
How to format your list of figures in Word to have left-aligned labels, centered captions, and right-aligned page numbers?
When I generate the list of figures automatically through Word, I’m getting the list of figures as shown below:
But, I want to achieve the following format of List of Figures. How to achieve the following format?
How to format your list of figures in Word to have left-aligned labels, centered captions, and right-aligned page numbers?When I generate the list of figures automatically through Word, I’m getting the list of figures as shown below:But, I want to achieve the following format of List of Figures. How to achieve the following format? Read More
Office 365 family – cannot edit shared calendar event on Android phone
Hi guys,
For few years I am experiencing this weird behavior on android phone of my wife in regards of use of our family calendar Will try to describe how it is set and what is happening:
We both have Office 365 family accounts (under one family)I have created new calendar under my account and shared to my wife account with edit permissions. If she use OWA she can work on events in our shared calendar without issues. If she try to edit event on Samsung mobile phone – in Samsung calendar app – she does not have edit option. She have delete option though.Tried in google calendar app and same – no edit option.If she create new event and save it – she has option to edit for approximately one minute. Than this option disappear. We have already changed phone at least twice and it is always the same.
So I have been looking around internet for similar issue reported, but did not find exactly this behavior …
Any thoughts are welcomed …
Hi guys, For few years I am experiencing this weird behavior on android phone of my wife in regards of use of our family calendar Will try to describe how it is set and what is happening:We both have Office 365 family accounts (under one family)I have created new calendar under my account and shared to my wife account with edit permissions. If she use OWA she can work on events in our shared calendar without issues. If she try to edit event on Samsung mobile phone – in Samsung calendar app – she does not have edit option. She have delete option though.Tried in google calendar app and same – no edit option.If she create new event and save it – she has option to edit for approximately one minute. Than this option disappear. We have already changed phone at least twice and it is always the same. So I have been looking around internet for similar issue reported, but did not find exactly this behavior … Any thoughts are welcomed … Read More
Learn Live Series – Crie uma LOB com OpenAI, Azure Communication Services e MS Graph (Parte I)
Na última quarta-feira, dia 05 de Maio, dei início a um novo workshop. Dessa vez, o foco foi em ensinar como criar uma aplicação Line Of Business com OpenAI, Azure Communication Service e Microsoft Graph Toolkit. E, durante essa live exploramos muitas coisas interessantes e legais que de fato essas tecnologias podem fazer por nós!
Vamos resumir essa primeira parte do Workshop agora mesmo!
O que foi abordado durante a Live?
Durante a live, discutimos aspectos fundamentais da integração da Inteligência Artificial, Comunicação e Dados Organizacionais em Aplicações de Negócios.
A sessão foi iniciada com uma contextualização sobre a importância da tecnologia na prevenção de desastres naturais, mediante a recente castrátofe ocorrida no Rio Grande do Sul com as enchentes e como a integração da Inteligência Artificial e a Tecnologia pode ajudar a prevenir futuros desastres.
Desenvolvimento da Aplicação LOB com Azure Communication Services, Microsoft Graph/ Microsoft Graph Toolkit com OpenAI
Nessa primeira parte do workshop, que a qual será dividida em outras partes, foi abordado do que se trata a aplicação a ser aprendida e desenvolvida.
Do que se trata a aplicação? Essa aplicação é uma ferramenta básica de gerenciamento de clientes que possibilita aos usuários administrar clientes e seus dados associados.
Ele é composto por um:
Front-End: foi desenvolvido com Angular + TypeScript
Back-End: que interage com APIs do Back-End para obter dados, acessar funcionalidades de Inteligência Artificial, enviar emails e SMS, usando justamente o Azure Communication Services. (falaremos mais sobre esse serviço no decorrer do artigo) e extraindo as informações desde um banco de dados (PostgreSQL) e também do Microsoft Graph para fins organizacionais.
Aqui está a arquitetura da aplicação:
Principais Componentes do Workshop
O projeto usa as seguintes tecnologias:
OpenAI: Utilizado para interpretar linguagem natural e executar tarefas complexas como conversão de linguagem para SQL.
Azure Communication Services: Demonstração de como incorporar funcionalidades de chamadas e mensagens dentro do aplicativo.
Microsoft Graph: utilizado para acessar dados organizacionais, reduzindo a necessidade de alternar entre aplicativos.
Microsoft Graph Toolkit: Utilizado para acessar dados do Microsoft Graph e integrar com o aplicativo.
O vídeo gravado pelo Dan Wahlin exemplifica como essa aplicação funciona e como ela pode ser útil para empresas que precisam gerenciar clientes e suas informações associadas.
O que é o Azure Communication Services?
O Azure Communication Services oferece APIs multicanal para incorporar funcionalidades de voz, vídeo, chat, SMS, email e muito mais em aplicações.
Esses serviços incluem APIs REST e SDKs de biblioteca cliente, facilitando a adição de recursos de comunicação sem necessidade de expertise nas tecnologias subjacentes.
O Azure Communication Services suporta diversos formatos:
Chamadas de voz e vídeo
Chat Rich Text
SMS
Email
Até mesmo o uso do WhatsApp pode ser integrado com o Azure Communication Services.
Além disso, o ACS é compatível com várias plataformas e linguagens, incluindo navegadores web (JavaScript), iOS (Swift), Android (Java) e Windows (.NET), com uma biblioteca de interface do usuário para acelerar o desenvolvimento de aplicativos para Web, iOS e Android. Ele é identidade agnóstica, dando controle sobre a identificação e autenticação dos clientes.
Se deseja saber os diferentes cenários de uso que você pode implementar com o Azure Communication Services, acesse aqui.
E, se você desejar saber mais sobre o Azure Communication Services, novamente o Dan Wahlin gravou um vídeo explicando como funciona o Azure Communication Services e como ele pode ser útil para empresas que precisam de funcionalidades de comunicação em suas aplicações.
O que é o Microsoft Graph?
O Microsoft Graph atua como um portal para os dados e insights do Microsoft 365. Ele oferece uma forma unificada de programar que permite acessar uma vasta quantidade de dados disponíveis no Microsoft 365, Windows e Enterprise Mobility + Security. Com o Microsoft Graph, você pode desenvolver aplicativos tanto para organizações quanto para consumidores, beneficiando-se dos dados que alcançam milhões de usuários.
Há inúmeros serviços do Microsoft Graph que você pode acessar, como:
Serviços principais do M365: Bookings, Calendar, Delve, Excel, Microsoft 365 compliance eDiscovery, Microsoft Pesquisa, OneDrive, OneNote, Outlook/Exchange, Pessoas (contatos do Outlook), Planner, SharePoint, Teams, To Do, Viva Insights.
Serviços de Enterprise Mobility + Security: Análise Avançada de Ameaças, Proteção Avançada contra Ameaças, Microsoft Entra ID, Identity Manager e Intune.
Serviços do Windows: atividades, dispositivos, notificações, Impressão Universal.
Serviços Dynamics 365 Business Central
Caso queira saber mais sobre o Microsoft Graph, acesse aqui.
Uso do Azure OpenAI Services ou OpenAI API
Durante a live foi explicado que o usuário caso deseje, pode optar em usar o Azure OpenAI Services ou a OpenAI API.
Porém, é importante ressaltar que o Azure OpenAI Services é um serviço que não está disponível para todos os usuários. Ele é um serviço em preview e, para usá-lo, é necessário solicitar acesso. Se você deseja fazer uso do serviço, precisará solicitar acesso e aguardar a aprovação.
Mas, caso você não tenha acesso ao Azure OpenAI Services, você pode usar a OpenAI API. A OpenAI API é um serviço que está disponível para todos os usuários e você pode começar a usá-lo imediatamente. Requer custos de uso, mas você pode começar a usar o serviço sem a necessidade de aprovação.
Iniciando a configuração do Projeto
Lembrando que, para seguir o passo a passo do workshop você poderá acessar a documentação oficial do workshop aqui.
Nesse primeiro momento, configuramos o projeto fazendo uso do Codespaces. Pois com o Codespaces, não precisaremos instalar nada em nossa máquina local. Tudo será feito na nuvem e, para isso, basta ter uma conta no GitHub.
Aproveitamos para executar o comando npm install para instalar as dependências do projeto. Tanto na pasta client e na pasta server. E, devido ao uso do Codespaces, podemos fazer uso do Docker para criar um container com o PostgreSQL. Simplesmente executando o comando docker-compose up -d para criar o container.
Se você não acompanhou a live, o projeto está disponível no GitHub. Você pode acessar o repositório aqui. Forke o repositório e siga o passo a passo do workshop.
E, finalmente criamos uma conta do Microsoft 365 Developer Program. Que é um programa gratuito que oferece uma conta de desenvolvedor do Microsoft 365, com acesso a um ambiente de desenvolvimento do Microsoft 365 E5, incluindo 25 licenças de usuário para uso de teste.
Recomendo que você crie uma conta no Microsoft 365 Developer Program para ter acesso a um ambiente de desenvolvimento do Microsoft 365 E5 e também para poder conseguir seguir com o tutorial!
Conclusão e Próximos Passos
Ao final do workshop, os participantes foram incentivados a aplicar o conhecimento adquirido em seus projetos, com Gláucia enfatizando a inevitável influência da inteligência artificial no futuro da tecnologia e desenvolvimento de software.
Próxima Live
Preparem-se para a próxima sessão da série Learn Live, onde continuaremos explorando novas integrações e expandindo os conhecimentos em aplicações LOB com OpenAI, Azure Communication Services e Microsoft Graph Toolkit.
A próxima parte do workshop será no dia 29 de Maio às 14h (horário de Brasília). Então, fique ligado(a) para não perder nenhuma live! E, aproveite e se inscreva no Canal do YouTube do Microsoft Reactor para não perder nenhuma live!
Lembrando que, essa série de vídeos continuará até Julho de 2024! Então, fique ligado(a) para não perder nenhuma live! E, aproveite e se inscreva no Canal do YouTube do Microsoft Reactor para não perder nenhuma live!
Recursos Adicionais
Sempre é muito importante ter acesso a recursos adicionais para aprimorar o conhecimento. Por isso, deixo aqui alguns links que podem ser úteis para vocês:
Link Oficial do Workshop
Curso Gratuito: Introdução aos Serviços de Comunicação do Azure
Curso Gratuito: Criar um aplicativo Web de chamadas de voz com os Serviços de Comunicação do Azure
Documentação do Azure Communication Services
Documentação do Microsoft Graph
Documentação do Microsoft Graph Toolkit
Espero que tenham gostado do artigo e até a próxima live!
Microsoft Tech Community – Latest Blogs –Read More
Navier-Stokes Solver With Finite Difference Method – Unexpected Results
Dear All,
I have been working on a Matlab script to implement a Navier-Stokes solver for the lid-driven wall problem but I think there is something wrong in my math because I am not getting the expected results if I compare my plots with benchmarks I have collected from online literatures and also I am not able to infer turbolence in my results by increasing the Re number.
I have also added a little function that checks for the boundaries conditions.
The solver is using the finite difference method to update the velocity and pressure fields, it calculates the tentative velocity using the momentum equations, corrects the pressure using the Poisson equation, finally it updates the velocity by using the corrected pressure. The boundary conditions are also applied.
This is the code if any of you fancy to help!
Alex
% Navier-Stokes Solver for Incompressible, Isothermal, and Newtonian Flow
clc
% Parameters
Lx = 1; % Length in x-direction
Ly = 1; % Length in y-direction
Nx = 32; % Number of grid points in x-direction
Ny = 32; % Number of grid points in y-direction
Re = 100; % Reynolds number
U_wall = 1; % Lid-driven wall velocity
tolerance = 1e-4; % Convergence tolerance
omega = 10; % frequency of oscillations
Amp = 0.1; % amplitude of oscillations
% Discretization
dx = Lx / (Nx – 1);
dy = Ly / (Ny – 1);
x = linspace(0, Lx, Nx);
y = linspace(0, Ly, Ny);
[X, Y] = meshgrid(x, y);
% Initialize velocity and pressure fields
u = zeros(Ny, Nx);
v = zeros(Ny, Nx);
p = zeros(Ny, Nx);
% Time stepping parameters
dt = 0.001;
max_iter = 50000;
% Main loop
for iter = 1:max_iter
% Calculate lid-driven wall velocity with sinusoidal variations
U_wall = 1 + Amp*sin(omega*dt*iter);
[u, v, p] = navier_stokes_solver(u, v, p, dx, dy, dt, Re, U_wall, tolerance);
if mod(iter, 100) == 0
fprintf(‘Iteration: %dn’, iter);
pause(0.01);
end
end
%Plot Pressure Field
contourf(X, Y, p);
title(‘Pressure’);
colorbar;
pause(0.01);
% Plot velocity field
figure;
quiver(X, Y, u, v);
title(‘Velocity Field’);
xlabel(‘x’);
ylabel(‘y’);
figure;
contourf(X,Y,u’,23,’LineColor’,’none’);
title(‘U-Velocity’);
colorbar;
%Plot stream function
N = 32; xstart = max(x)*rand(N,1); ystart = max(y)*rand(N,1);
%[X,Y] = meshgrid(x,y);
figure; h=streamline(X,Y,u’,v’,xstart,ystart,[0.1, 200]);
title(‘Stream Function’); xlabel(‘x-location’); ylabel(‘y-location’)
axis(‘equal’,[0 Lx 0 Ly]); set(h,’color’,’k’)
boundary_condition_tests(u, v, U_wall);
function [u_new, v_new, p_new] = navier_stokes_solver(u, v, p, dx, dy, dt, Re, U_wall, tolerance)
[Ny, Nx] = size(u);
% Initialize temporary fields
u_new = u;
v_new = v;
p_new = p;
% Calculate the tentative velocity (u*) using momentum equations
for i = 2:Ny – 1
for j = 2:Nx – 1
% Viscous acceleration term (in x-direction)
viscous_x_term = (1 / Re) * (u(i, j + 1) – 2 * u(i, j) + u(i, j – 1)) / (dx^2);
% Viscous acceleration term (in y-direction)
viscous_y_term = (1 / Re) * (u(i + 1, j) – 2 * u(i, j) + u(i – 1, j)) / (dy^2);
u_new(i, j) = u(i, j) + dt * (viscous_x_term + viscous_y_term);
% Viscous term in x-direction
viscous_v_x_term = (1 / Re) * (v(i, j + 1) – 2 * v(i, j) + v(i, j – 1)) / (dx^2);
viscous_v_y_term = (1 / Re) * (v(i + 1, j) – 2 * v(i, j) + v(i – 1, j)) / (dy^2);
v_new(i, j) = v(i, j) + dt * (viscous_v_x_term + viscous_v_y_term);
end
end
% Pressure correction (Poisson equation)
p_initial = p_new; % Store the initial pressure field
maxe = 1;
while maxe > tolerance
p_old = p_new;
for i = 2:Ny – 1
for j = 2:Nx – 1
p_new(i, j) = (1 / 4) * (p_old(i, j + 1) + p_old(i, j – 1) …
+ p_old(i + 1, j) + p_old(i – 1, j) …
– dx * (u_new(i, j + 1) – u_new(i, j – 1)) / 2 …
– dy * (v_new(i + 1, j) – v_new(i – 1, j)) / 2);
end
end
maxe = max(max(abs(p_new – p_old)));
end
%Update velocity with pressure correction using the initial pressure field
for i = 2:Ny – 1
for j = 2:Nx – 1
u_new(i, j) = u_new(i, j) – dt * (p_initial(i, j + 1) – p_initial(i, j – 1)) / (2 * dx);
v_new(i, j) = v_new(i, j) – dt * (p_initial(i + 1, j) – p_initial(i – 1, j)) / (2 * dy);
end
end
% Boundary conditions
u_new(1, 🙂 = 0;
u_new(end, 🙂 = 0;
u_new(:, 1) = 0;
u_new(:, end) = 2 * U_wall – u_new(:, end – 1); % Moving lid
v_new(1, 🙂 = -v_new(2, :);
v_new(end, 🙂 = -v_new(end – 1, :);
v_new(:, 1) = 0;
v_new(:, end) = 0;
p_new(1, 🙂 = p_new(2, :);
p_new(end, 🙂 = p_new(end – 1, :);
p_new(:, 1) = p_new(:, 2);
p_new(:, end) = p_new(:, end – 1);
end
function boundary_condition_tests(u, v, U_wall)
fprintf(‘Boundary Condition Testn’);
% Bottom wall u-velocity
bottom_wall_u = u(1, :);
bottom_wall_u_test = all(abs(bottom_wall_u) < 1e-6);
if bottom_wall_u_test
fprintf(‘Bottom wall u-velocity: Passn’);
else
fprintf(‘Bottom wall u-velocity: Fail (Actual value: %s)n’, mat2str(bottom_wall_u));
end
% Top wall u-velocity
top_wall_u = u(end, :);
top_wall_u_test = all(abs(top_wall_u – 2 * U_wall) < 1e-6);
if top_wall_u_test
fprintf(‘Top wall u-velocity: Passn’);
else
fprintf(‘Top wall u-velocity: Fail (Actual value: %s)n’, mat2str(top_wall_u));
end
% Left and right wall u-velocity
left_wall_u = u(:, 1);
right_wall_u = u(:, end);
left_right_wall_u_test = all(abs(left_wall_u) < 1e-6) && all(abs(right_wall_u) < 1e-6);
if left_right_wall_u_test
fprintf(‘Left and right wall u-velocity: Passn’);
else
fprintf(‘Left and right wall u-velocity: Fail (Actual value: Left – %s, Right – %s)n’, mat2str(left_wall_u), mat2str(right_wall_u));
end
% Left and right wall v-velocity
left_wall_v = v(:, 1);
right_wall_v = v(:, end);
left_right_wall_v_test = all(abs(left_wall_v) < 1e-6) && all(abs(right_wall_v) < 1e-6);
if left_right_wall_v_test
fprintf(‘Left and right wall v-velocity: Passn’);
else
fprintf(‘Left and right wall v-velocity: Fail (Actual value: Left – %s, Right – %s)n’, mat2str(left_wall_v), mat2str(right_wall_v));
end
% Bottom and top wall v-velocity
bottom_wall_v = v(1, :);
top_wall_v = v(end, :);
bottom_top_wall_v_test = all(abs(bottom_wall_v + v(2, :)) < 1e-6) && all(abs(top_wall_v + v(end – 1, :)) < 1e-6);
if bottom_top_wall_v_test
fprintf(‘Bottom and top wall v-velocity: Passn’);
else
fprintf(‘Bottom and top wall v-velocity: Fail (Actual value: Bottom – %s, Top – %s)n’, mat2str(bottom_wall_v), mat2str(top_wall_v));
end
% Count the total failed boundary conditions
failed_count = sum([~bottom_wall_u_test, ~top_wall_u_test, ~left_right_wall_u_test, ~left_right_wall_v_test, ~bottom_top_wall_v_test]);
fprintf(‘Total failed boundary conditions: %dn’, failed_count);
endDear All,
I have been working on a Matlab script to implement a Navier-Stokes solver for the lid-driven wall problem but I think there is something wrong in my math because I am not getting the expected results if I compare my plots with benchmarks I have collected from online literatures and also I am not able to infer turbolence in my results by increasing the Re number.
I have also added a little function that checks for the boundaries conditions.
The solver is using the finite difference method to update the velocity and pressure fields, it calculates the tentative velocity using the momentum equations, corrects the pressure using the Poisson equation, finally it updates the velocity by using the corrected pressure. The boundary conditions are also applied.
This is the code if any of you fancy to help!
Alex
% Navier-Stokes Solver for Incompressible, Isothermal, and Newtonian Flow
clc
% Parameters
Lx = 1; % Length in x-direction
Ly = 1; % Length in y-direction
Nx = 32; % Number of grid points in x-direction
Ny = 32; % Number of grid points in y-direction
Re = 100; % Reynolds number
U_wall = 1; % Lid-driven wall velocity
tolerance = 1e-4; % Convergence tolerance
omega = 10; % frequency of oscillations
Amp = 0.1; % amplitude of oscillations
% Discretization
dx = Lx / (Nx – 1);
dy = Ly / (Ny – 1);
x = linspace(0, Lx, Nx);
y = linspace(0, Ly, Ny);
[X, Y] = meshgrid(x, y);
% Initialize velocity and pressure fields
u = zeros(Ny, Nx);
v = zeros(Ny, Nx);
p = zeros(Ny, Nx);
% Time stepping parameters
dt = 0.001;
max_iter = 50000;
% Main loop
for iter = 1:max_iter
% Calculate lid-driven wall velocity with sinusoidal variations
U_wall = 1 + Amp*sin(omega*dt*iter);
[u, v, p] = navier_stokes_solver(u, v, p, dx, dy, dt, Re, U_wall, tolerance);
if mod(iter, 100) == 0
fprintf(‘Iteration: %dn’, iter);
pause(0.01);
end
end
%Plot Pressure Field
contourf(X, Y, p);
title(‘Pressure’);
colorbar;
pause(0.01);
% Plot velocity field
figure;
quiver(X, Y, u, v);
title(‘Velocity Field’);
xlabel(‘x’);
ylabel(‘y’);
figure;
contourf(X,Y,u’,23,’LineColor’,’none’);
title(‘U-Velocity’);
colorbar;
%Plot stream function
N = 32; xstart = max(x)*rand(N,1); ystart = max(y)*rand(N,1);
%[X,Y] = meshgrid(x,y);
figure; h=streamline(X,Y,u’,v’,xstart,ystart,[0.1, 200]);
title(‘Stream Function’); xlabel(‘x-location’); ylabel(‘y-location’)
axis(‘equal’,[0 Lx 0 Ly]); set(h,’color’,’k’)
boundary_condition_tests(u, v, U_wall);
function [u_new, v_new, p_new] = navier_stokes_solver(u, v, p, dx, dy, dt, Re, U_wall, tolerance)
[Ny, Nx] = size(u);
% Initialize temporary fields
u_new = u;
v_new = v;
p_new = p;
% Calculate the tentative velocity (u*) using momentum equations
for i = 2:Ny – 1
for j = 2:Nx – 1
% Viscous acceleration term (in x-direction)
viscous_x_term = (1 / Re) * (u(i, j + 1) – 2 * u(i, j) + u(i, j – 1)) / (dx^2);
% Viscous acceleration term (in y-direction)
viscous_y_term = (1 / Re) * (u(i + 1, j) – 2 * u(i, j) + u(i – 1, j)) / (dy^2);
u_new(i, j) = u(i, j) + dt * (viscous_x_term + viscous_y_term);
% Viscous term in x-direction
viscous_v_x_term = (1 / Re) * (v(i, j + 1) – 2 * v(i, j) + v(i, j – 1)) / (dx^2);
viscous_v_y_term = (1 / Re) * (v(i + 1, j) – 2 * v(i, j) + v(i – 1, j)) / (dy^2);
v_new(i, j) = v(i, j) + dt * (viscous_v_x_term + viscous_v_y_term);
end
end
% Pressure correction (Poisson equation)
p_initial = p_new; % Store the initial pressure field
maxe = 1;
while maxe > tolerance
p_old = p_new;
for i = 2:Ny – 1
for j = 2:Nx – 1
p_new(i, j) = (1 / 4) * (p_old(i, j + 1) + p_old(i, j – 1) …
+ p_old(i + 1, j) + p_old(i – 1, j) …
– dx * (u_new(i, j + 1) – u_new(i, j – 1)) / 2 …
– dy * (v_new(i + 1, j) – v_new(i – 1, j)) / 2);
end
end
maxe = max(max(abs(p_new – p_old)));
end
%Update velocity with pressure correction using the initial pressure field
for i = 2:Ny – 1
for j = 2:Nx – 1
u_new(i, j) = u_new(i, j) – dt * (p_initial(i, j + 1) – p_initial(i, j – 1)) / (2 * dx);
v_new(i, j) = v_new(i, j) – dt * (p_initial(i + 1, j) – p_initial(i – 1, j)) / (2 * dy);
end
end
% Boundary conditions
u_new(1, 🙂 = 0;
u_new(end, 🙂 = 0;
u_new(:, 1) = 0;
u_new(:, end) = 2 * U_wall – u_new(:, end – 1); % Moving lid
v_new(1, 🙂 = -v_new(2, :);
v_new(end, 🙂 = -v_new(end – 1, :);
v_new(:, 1) = 0;
v_new(:, end) = 0;
p_new(1, 🙂 = p_new(2, :);
p_new(end, 🙂 = p_new(end – 1, :);
p_new(:, 1) = p_new(:, 2);
p_new(:, end) = p_new(:, end – 1);
end
function boundary_condition_tests(u, v, U_wall)
fprintf(‘Boundary Condition Testn’);
% Bottom wall u-velocity
bottom_wall_u = u(1, :);
bottom_wall_u_test = all(abs(bottom_wall_u) < 1e-6);
if bottom_wall_u_test
fprintf(‘Bottom wall u-velocity: Passn’);
else
fprintf(‘Bottom wall u-velocity: Fail (Actual value: %s)n’, mat2str(bottom_wall_u));
end
% Top wall u-velocity
top_wall_u = u(end, :);
top_wall_u_test = all(abs(top_wall_u – 2 * U_wall) < 1e-6);
if top_wall_u_test
fprintf(‘Top wall u-velocity: Passn’);
else
fprintf(‘Top wall u-velocity: Fail (Actual value: %s)n’, mat2str(top_wall_u));
end
% Left and right wall u-velocity
left_wall_u = u(:, 1);
right_wall_u = u(:, end);
left_right_wall_u_test = all(abs(left_wall_u) < 1e-6) && all(abs(right_wall_u) < 1e-6);
if left_right_wall_u_test
fprintf(‘Left and right wall u-velocity: Passn’);
else
fprintf(‘Left and right wall u-velocity: Fail (Actual value: Left – %s, Right – %s)n’, mat2str(left_wall_u), mat2str(right_wall_u));
end
% Left and right wall v-velocity
left_wall_v = v(:, 1);
right_wall_v = v(:, end);
left_right_wall_v_test = all(abs(left_wall_v) < 1e-6) && all(abs(right_wall_v) < 1e-6);
if left_right_wall_v_test
fprintf(‘Left and right wall v-velocity: Passn’);
else
fprintf(‘Left and right wall v-velocity: Fail (Actual value: Left – %s, Right – %s)n’, mat2str(left_wall_v), mat2str(right_wall_v));
end
% Bottom and top wall v-velocity
bottom_wall_v = v(1, :);
top_wall_v = v(end, :);
bottom_top_wall_v_test = all(abs(bottom_wall_v + v(2, :)) < 1e-6) && all(abs(top_wall_v + v(end – 1, :)) < 1e-6);
if bottom_top_wall_v_test
fprintf(‘Bottom and top wall v-velocity: Passn’);
else
fprintf(‘Bottom and top wall v-velocity: Fail (Actual value: Bottom – %s, Top – %s)n’, mat2str(bottom_wall_v), mat2str(top_wall_v));
end
% Count the total failed boundary conditions
failed_count = sum([~bottom_wall_u_test, ~top_wall_u_test, ~left_right_wall_u_test, ~left_right_wall_v_test, ~bottom_top_wall_v_test]);
fprintf(‘Total failed boundary conditions: %dn’, failed_count);
end Dear All,
I have been working on a Matlab script to implement a Navier-Stokes solver for the lid-driven wall problem but I think there is something wrong in my math because I am not getting the expected results if I compare my plots with benchmarks I have collected from online literatures and also I am not able to infer turbolence in my results by increasing the Re number.
I have also added a little function that checks for the boundaries conditions.
The solver is using the finite difference method to update the velocity and pressure fields, it calculates the tentative velocity using the momentum equations, corrects the pressure using the Poisson equation, finally it updates the velocity by using the corrected pressure. The boundary conditions are also applied.
This is the code if any of you fancy to help!
Alex
% Navier-Stokes Solver for Incompressible, Isothermal, and Newtonian Flow
clc
% Parameters
Lx = 1; % Length in x-direction
Ly = 1; % Length in y-direction
Nx = 32; % Number of grid points in x-direction
Ny = 32; % Number of grid points in y-direction
Re = 100; % Reynolds number
U_wall = 1; % Lid-driven wall velocity
tolerance = 1e-4; % Convergence tolerance
omega = 10; % frequency of oscillations
Amp = 0.1; % amplitude of oscillations
% Discretization
dx = Lx / (Nx – 1);
dy = Ly / (Ny – 1);
x = linspace(0, Lx, Nx);
y = linspace(0, Ly, Ny);
[X, Y] = meshgrid(x, y);
% Initialize velocity and pressure fields
u = zeros(Ny, Nx);
v = zeros(Ny, Nx);
p = zeros(Ny, Nx);
% Time stepping parameters
dt = 0.001;
max_iter = 50000;
% Main loop
for iter = 1:max_iter
% Calculate lid-driven wall velocity with sinusoidal variations
U_wall = 1 + Amp*sin(omega*dt*iter);
[u, v, p] = navier_stokes_solver(u, v, p, dx, dy, dt, Re, U_wall, tolerance);
if mod(iter, 100) == 0
fprintf(‘Iteration: %dn’, iter);
pause(0.01);
end
end
%Plot Pressure Field
contourf(X, Y, p);
title(‘Pressure’);
colorbar;
pause(0.01);
% Plot velocity field
figure;
quiver(X, Y, u, v);
title(‘Velocity Field’);
xlabel(‘x’);
ylabel(‘y’);
figure;
contourf(X,Y,u’,23,’LineColor’,’none’);
title(‘U-Velocity’);
colorbar;
%Plot stream function
N = 32; xstart = max(x)*rand(N,1); ystart = max(y)*rand(N,1);
%[X,Y] = meshgrid(x,y);
figure; h=streamline(X,Y,u’,v’,xstart,ystart,[0.1, 200]);
title(‘Stream Function’); xlabel(‘x-location’); ylabel(‘y-location’)
axis(‘equal’,[0 Lx 0 Ly]); set(h,’color’,’k’)
boundary_condition_tests(u, v, U_wall);
function [u_new, v_new, p_new] = navier_stokes_solver(u, v, p, dx, dy, dt, Re, U_wall, tolerance)
[Ny, Nx] = size(u);
% Initialize temporary fields
u_new = u;
v_new = v;
p_new = p;
% Calculate the tentative velocity (u*) using momentum equations
for i = 2:Ny – 1
for j = 2:Nx – 1
% Viscous acceleration term (in x-direction)
viscous_x_term = (1 / Re) * (u(i, j + 1) – 2 * u(i, j) + u(i, j – 1)) / (dx^2);
% Viscous acceleration term (in y-direction)
viscous_y_term = (1 / Re) * (u(i + 1, j) – 2 * u(i, j) + u(i – 1, j)) / (dy^2);
u_new(i, j) = u(i, j) + dt * (viscous_x_term + viscous_y_term);
% Viscous term in x-direction
viscous_v_x_term = (1 / Re) * (v(i, j + 1) – 2 * v(i, j) + v(i, j – 1)) / (dx^2);
viscous_v_y_term = (1 / Re) * (v(i + 1, j) – 2 * v(i, j) + v(i – 1, j)) / (dy^2);
v_new(i, j) = v(i, j) + dt * (viscous_v_x_term + viscous_v_y_term);
end
end
% Pressure correction (Poisson equation)
p_initial = p_new; % Store the initial pressure field
maxe = 1;
while maxe > tolerance
p_old = p_new;
for i = 2:Ny – 1
for j = 2:Nx – 1
p_new(i, j) = (1 / 4) * (p_old(i, j + 1) + p_old(i, j – 1) …
+ p_old(i + 1, j) + p_old(i – 1, j) …
– dx * (u_new(i, j + 1) – u_new(i, j – 1)) / 2 …
– dy * (v_new(i + 1, j) – v_new(i – 1, j)) / 2);
end
end
maxe = max(max(abs(p_new – p_old)));
end
%Update velocity with pressure correction using the initial pressure field
for i = 2:Ny – 1
for j = 2:Nx – 1
u_new(i, j) = u_new(i, j) – dt * (p_initial(i, j + 1) – p_initial(i, j – 1)) / (2 * dx);
v_new(i, j) = v_new(i, j) – dt * (p_initial(i + 1, j) – p_initial(i – 1, j)) / (2 * dy);
end
end
% Boundary conditions
u_new(1, 🙂 = 0;
u_new(end, 🙂 = 0;
u_new(:, 1) = 0;
u_new(:, end) = 2 * U_wall – u_new(:, end – 1); % Moving lid
v_new(1, 🙂 = -v_new(2, :);
v_new(end, 🙂 = -v_new(end – 1, :);
v_new(:, 1) = 0;
v_new(:, end) = 0;
p_new(1, 🙂 = p_new(2, :);
p_new(end, 🙂 = p_new(end – 1, :);
p_new(:, 1) = p_new(:, 2);
p_new(:, end) = p_new(:, end – 1);
end
function boundary_condition_tests(u, v, U_wall)
fprintf(‘Boundary Condition Testn’);
% Bottom wall u-velocity
bottom_wall_u = u(1, :);
bottom_wall_u_test = all(abs(bottom_wall_u) < 1e-6);
if bottom_wall_u_test
fprintf(‘Bottom wall u-velocity: Passn’);
else
fprintf(‘Bottom wall u-velocity: Fail (Actual value: %s)n’, mat2str(bottom_wall_u));
end
% Top wall u-velocity
top_wall_u = u(end, :);
top_wall_u_test = all(abs(top_wall_u – 2 * U_wall) < 1e-6);
if top_wall_u_test
fprintf(‘Top wall u-velocity: Passn’);
else
fprintf(‘Top wall u-velocity: Fail (Actual value: %s)n’, mat2str(top_wall_u));
end
% Left and right wall u-velocity
left_wall_u = u(:, 1);
right_wall_u = u(:, end);
left_right_wall_u_test = all(abs(left_wall_u) < 1e-6) && all(abs(right_wall_u) < 1e-6);
if left_right_wall_u_test
fprintf(‘Left and right wall u-velocity: Passn’);
else
fprintf(‘Left and right wall u-velocity: Fail (Actual value: Left – %s, Right – %s)n’, mat2str(left_wall_u), mat2str(right_wall_u));
end
% Left and right wall v-velocity
left_wall_v = v(:, 1);
right_wall_v = v(:, end);
left_right_wall_v_test = all(abs(left_wall_v) < 1e-6) && all(abs(right_wall_v) < 1e-6);
if left_right_wall_v_test
fprintf(‘Left and right wall v-velocity: Passn’);
else
fprintf(‘Left and right wall v-velocity: Fail (Actual value: Left – %s, Right – %s)n’, mat2str(left_wall_v), mat2str(right_wall_v));
end
% Bottom and top wall v-velocity
bottom_wall_v = v(1, :);
top_wall_v = v(end, :);
bottom_top_wall_v_test = all(abs(bottom_wall_v + v(2, :)) < 1e-6) && all(abs(top_wall_v + v(end – 1, :)) < 1e-6);
if bottom_top_wall_v_test
fprintf(‘Bottom and top wall v-velocity: Passn’);
else
fprintf(‘Bottom and top wall v-velocity: Fail (Actual value: Bottom – %s, Top – %s)n’, mat2str(bottom_wall_v), mat2str(top_wall_v));
end
% Count the total failed boundary conditions
failed_count = sum([~bottom_wall_u_test, ~top_wall_u_test, ~left_right_wall_u_test, ~left_right_wall_v_test, ~bottom_top_wall_v_test]);
fprintf(‘Total failed boundary conditions: %dn’, failed_count);
end navier stokes solver, finite differences MATLAB Answers — New Questions
Startup Showcase: Cleverdist
ZoomIn3D GenAI-Enabled Voice-Controlled 3D User Interface
Founders Hub Benefits
What benefits have they been using? prototyping fast and with scale using Azure
ZoomIn3D Product Demo
Join Microsoft for Startups Founders’ Hub today!
This initiative is designed to be inclusive, welcoming individuals with a vision to innovate, without the prerequisite of prior funding.
Microsoft Tech Community – Latest Blogs –Read More
math model of neural network fitting
Hi, I complete the neural network fitting work, but how can I get this math model ? tksHi, I complete the neural network fitting work, but how can I get this math model ? tks Hi, I complete the neural network fitting work, but how can I get this math model ? tks neural network, maching learning, deep learning MATLAB Answers — New Questions
For loop for fibonacci series
i am supposed to write a fibonacci series that calculate up to n term and (n-1) term but i am stuck at calculating the (n-1)term. can anyone help? ( i am new to matlab)
a = 0;
b = 1;
x = n-1;
n = input(‘Enter number of term desired’);
for i = 1:n %term for n
fprintf(‘t’)
fprintf(‘%d’,a);
c = a + b;
a = b;
b = c;
end
for i = n:x %term for n-1
fprintf(‘t’)
fprintf(‘%d’,a);
c = a + b;
a = b;
b = c;
endi am supposed to write a fibonacci series that calculate up to n term and (n-1) term but i am stuck at calculating the (n-1)term. can anyone help? ( i am new to matlab)
a = 0;
b = 1;
x = n-1;
n = input(‘Enter number of term desired’);
for i = 1:n %term for n
fprintf(‘t’)
fprintf(‘%d’,a);
c = a + b;
a = b;
b = c;
end
for i = n:x %term for n-1
fprintf(‘t’)
fprintf(‘%d’,a);
c = a + b;
a = b;
b = c;
end i am supposed to write a fibonacci series that calculate up to n term and (n-1) term but i am stuck at calculating the (n-1)term. can anyone help? ( i am new to matlab)
a = 0;
b = 1;
x = n-1;
n = input(‘Enter number of term desired’);
for i = 1:n %term for n
fprintf(‘t’)
fprintf(‘%d’,a);
c = a + b;
a = b;
b = c;
end
for i = n:x %term for n-1
fprintf(‘t’)
fprintf(‘%d’,a);
c = a + b;
a = b;
b = c;
end for loop MATLAB Answers — New Questions
Neural Network Fitting each layers neurous number
Hi, how can I know the neural network fitting neurous number in each layers ? and how can I modify ? tksHi, how can I know the neural network fitting neurous number in each layers ? and how can I modify ? tks Hi, how can I know the neural network fitting neurous number in each layers ? and how can I modify ? tks maching learning, neural network fitting, deep learning MATLAB Answers — New Questions
Non-linear Algebraic 36 equations unsloved
Hi forum
I have 36 Non-linear Algebraic equations with 36 unknowns to find out.
‘solve’ comand failed.
‘fsolve’ comand requires initial choices which I dont have.
Any idea, how to solve? Please helpHi forum
I have 36 Non-linear Algebraic equations with 36 unknowns to find out.
‘solve’ comand failed.
‘fsolve’ comand requires initial choices which I dont have.
Any idea, how to solve? Please help Hi forum
I have 36 Non-linear Algebraic equations with 36 unknowns to find out.
‘solve’ comand failed.
‘fsolve’ comand requires initial choices which I dont have.
Any idea, how to solve? Please help non-linear algebraic 36 equations unsloved MATLAB Answers — New Questions
How do I add FreeRTOS support in the C2000 blockset (TMS320F28388x) in MATLAB?”
I am using the C2000 blockset for TMS320F28388x-based development. I want to add a FreeRTOS configuration block in Simulink so that RTOS-related configurations can be done through the Simulink library block.
I am using matlab 2023a version and C2000 blockset v4.0.0.0.
I am unable to find the FreeRTOS configuration block in the C2000 blockset. Could you please help me with configuring FreeRTOS through a Simulink block?I am using the C2000 blockset for TMS320F28388x-based development. I want to add a FreeRTOS configuration block in Simulink so that RTOS-related configurations can be done through the Simulink library block.
I am using matlab 2023a version and C2000 blockset v4.0.0.0.
I am unable to find the FreeRTOS configuration block in the C2000 blockset. Could you please help me with configuring FreeRTOS through a Simulink block? I am using the C2000 blockset for TMS320F28388x-based development. I want to add a FreeRTOS configuration block in Simulink so that RTOS-related configurations can be done through the Simulink library block.
I am using matlab 2023a version and C2000 blockset v4.0.0.0.
I am unable to find the FreeRTOS configuration block in the C2000 blockset. Could you please help me with configuring FreeRTOS through a Simulink block? c2000, simulink, matlab, embedded coder, s-function, c2000 blockset, embedded matlab function, matlab function, matlab code, matlab library MATLAB Answers — New Questions