Category: Matlab
Category Archives: Matlab
how to simulate communication channel in control toolbox
Is there a way to simulate a communication channel in a simulink like the one shown below, using some block like the BSC or the AWGN channel, in order to simulate an error produced directly by the communication channel being used. I need it to be an element that can be easily incorporated, since it is to perform simulation activities in a classroom.
ThanksIs there a way to simulate a communication channel in a simulink like the one shown below, using some block like the BSC or the AWGN channel, in order to simulate an error produced directly by the communication channel being used. I need it to be an element that can be easily incorporated, since it is to perform simulation activities in a classroom.
Thanks Is there a way to simulate a communication channel in a simulink like the one shown below, using some block like the BSC or the AWGN channel, in order to simulate an error produced directly by the communication channel being used. I need it to be an element that can be easily incorporated, since it is to perform simulation activities in a classroom.
Thanks communication, control toolbox MATLAB Answers — New Questions
​
how to delete nan values from array columns without losing data from other columns
i have a huge file from a lab expremient
every run gives me 4 columns and every 2 out of the 4 start with nan then 2 nan vars and end with nan and 3 nan vars i want to delet the nan values without losing any data so that when i try to make graphs from it every graph will have enough inputs and neither of them get lost
i am espisally troubled by the second 2 columns of every 4 and how to deal with themi have a huge file from a lab expremient
every run gives me 4 columns and every 2 out of the 4 start with nan then 2 nan vars and end with nan and 3 nan vars i want to delet the nan values without losing any data so that when i try to make graphs from it every graph will have enough inputs and neither of them get lost
i am espisally troubled by the second 2 columns of every 4 and how to deal with them i have a huge file from a lab expremient
every run gives me 4 columns and every 2 out of the 4 start with nan then 2 nan vars and end with nan and 3 nan vars i want to delet the nan values without losing any data so that when i try to make graphs from it every graph will have enough inputs and neither of them get lost
i am espisally troubled by the second 2 columns of every 4 and how to deal with them data, import, nan MATLAB Answers — New Questions
​
How to fit curve based on two related independent variables ?
Hello, I met this problem when doing curve fitting with ‘fit’ function, I wish get some help.
For independent variables, I have:
x=[1 2 3 4 5 6];
y=[1 1 1 2 2 2];
The dependent variable is:
z=[10 11 12 13 14 15];
My function is written as:
z=a*(x/y+x)
a is the coefficient to be evaluated. x and y varies but related, so x and y don’t form a 2D plane. the result of ‘x/y’ in the function is actually supposed to be equivalent to ‘x./y’.
I tried designating y as problem-depedent parameter (not working, as only one value is allowed for one parameter)
I tried using ‘x./y’ in the function, but it seems ‘fit’ still reads it as a 2D surface.
Please share your opinions on this problem, I have n’t figure out the right way to do it yet. I appreciate a lot your help.
Sincerely
chenHello, I met this problem when doing curve fitting with ‘fit’ function, I wish get some help.
For independent variables, I have:
x=[1 2 3 4 5 6];
y=[1 1 1 2 2 2];
The dependent variable is:
z=[10 11 12 13 14 15];
My function is written as:
z=a*(x/y+x)
a is the coefficient to be evaluated. x and y varies but related, so x and y don’t form a 2D plane. the result of ‘x/y’ in the function is actually supposed to be equivalent to ‘x./y’.
I tried designating y as problem-depedent parameter (not working, as only one value is allowed for one parameter)
I tried using ‘x./y’ in the function, but it seems ‘fit’ still reads it as a 2D surface.
Please share your opinions on this problem, I have n’t figure out the right way to do it yet. I appreciate a lot your help.
Sincerely
chen Hello, I met this problem when doing curve fitting with ‘fit’ function, I wish get some help.
For independent variables, I have:
x=[1 2 3 4 5 6];
y=[1 1 1 2 2 2];
The dependent variable is:
z=[10 11 12 13 14 15];
My function is written as:
z=a*(x/y+x)
a is the coefficient to be evaluated. x and y varies but related, so x and y don’t form a 2D plane. the result of ‘x/y’ in the function is actually supposed to be equivalent to ‘x./y’.
I tried designating y as problem-depedent parameter (not working, as only one value is allowed for one parameter)
I tried using ‘x./y’ in the function, but it seems ‘fit’ still reads it as a 2D surface.
Please share your opinions on this problem, I have n’t figure out the right way to do it yet. I appreciate a lot your help.
Sincerely
chen fit related independent variables MATLAB Answers — New Questions
​
Difficulty in Calculating Signal Frequency with an Offset
So I wrote a Matlab program that calculates and plots some key values of a signal. The signal is stored in a .csv file.
The problem is that the calculation of the frequency only works for signals that don’t have an offset.
I would appreciate any kind of help since I can’t seem to figure it out on my own.
Matlab program:
% Reading .csv
data = readmatrix(‘Sinus.csv’);
% Extract time and voltage columns
time = data(:, 1);
voltage = data(:, 2);
% Calculate peak value
peak_value = max(abs(voltage));
% Calculate arithmetic mean in mV
mean_value = mean(voltage) * 1000; % Conversion from V to mV
% Calculate rectified value
rectified_value = mean(abs(voltage));
% Calculate RMS (Root Mean Square) value
rms_value = rms(voltage);
% Calculate form factor
form_factor = rms_value / rectified_value;
% Calculate crest factor
crest_factor = peak_value / rms_value;
% Calculate sampling frequency (Assumption: uniformly sampled signal)
sampling_frequency = 1 / (time(2) – time(1));
% Calculate FFT (Fast Fourier Transform) of the signal
N = length(voltage);
Y = fft(voltage);
f = sampling_frequency*(0:(N/2))/N;
% Find the index of the maximum in the frequency domain
[~, max_index] = max(abs(Y(1:N/2+1)));
% Extract frequency at the maximum
frequency = f(max_index);
% Calculate period duration in ms
period_duration = 1/frequency * 1000; % Conversion from s to ms
I will also add the program and 2 example signals (one with and one without offset).
Thank you for your time!So I wrote a Matlab program that calculates and plots some key values of a signal. The signal is stored in a .csv file.
The problem is that the calculation of the frequency only works for signals that don’t have an offset.
I would appreciate any kind of help since I can’t seem to figure it out on my own.
Matlab program:
% Reading .csv
data = readmatrix(‘Sinus.csv’);
% Extract time and voltage columns
time = data(:, 1);
voltage = data(:, 2);
% Calculate peak value
peak_value = max(abs(voltage));
% Calculate arithmetic mean in mV
mean_value = mean(voltage) * 1000; % Conversion from V to mV
% Calculate rectified value
rectified_value = mean(abs(voltage));
% Calculate RMS (Root Mean Square) value
rms_value = rms(voltage);
% Calculate form factor
form_factor = rms_value / rectified_value;
% Calculate crest factor
crest_factor = peak_value / rms_value;
% Calculate sampling frequency (Assumption: uniformly sampled signal)
sampling_frequency = 1 / (time(2) – time(1));
% Calculate FFT (Fast Fourier Transform) of the signal
N = length(voltage);
Y = fft(voltage);
f = sampling_frequency*(0:(N/2))/N;
% Find the index of the maximum in the frequency domain
[~, max_index] = max(abs(Y(1:N/2+1)));
% Extract frequency at the maximum
frequency = f(max_index);
% Calculate period duration in ms
period_duration = 1/frequency * 1000; % Conversion from s to ms
I will also add the program and 2 example signals (one with and one without offset).
Thank you for your time! So I wrote a Matlab program that calculates and plots some key values of a signal. The signal is stored in a .csv file.
The problem is that the calculation of the frequency only works for signals that don’t have an offset.
I would appreciate any kind of help since I can’t seem to figure it out on my own.
Matlab program:
% Reading .csv
data = readmatrix(‘Sinus.csv’);
% Extract time and voltage columns
time = data(:, 1);
voltage = data(:, 2);
% Calculate peak value
peak_value = max(abs(voltage));
% Calculate arithmetic mean in mV
mean_value = mean(voltage) * 1000; % Conversion from V to mV
% Calculate rectified value
rectified_value = mean(abs(voltage));
% Calculate RMS (Root Mean Square) value
rms_value = rms(voltage);
% Calculate form factor
form_factor = rms_value / rectified_value;
% Calculate crest factor
crest_factor = peak_value / rms_value;
% Calculate sampling frequency (Assumption: uniformly sampled signal)
sampling_frequency = 1 / (time(2) – time(1));
% Calculate FFT (Fast Fourier Transform) of the signal
N = length(voltage);
Y = fft(voltage);
f = sampling_frequency*(0:(N/2))/N;
% Find the index of the maximum in the frequency domain
[~, max_index] = max(abs(Y(1:N/2+1)));
% Extract frequency at the maximum
frequency = f(max_index);
% Calculate period duration in ms
period_duration = 1/frequency * 1000; % Conversion from s to ms
I will also add the program and 2 example signals (one with and one without offset).
Thank you for your time! fft, frequency, calculation, signal, signal processing, csv MATLAB Answers — New Questions
​
How to solve nonlinear equation?
Hello,
I wrote the following code to derive an analytical solution to nonlinear equation but it gives an error. Could you please help me to fix it? Or any suggestion to solve in an analytical way. Thanks
syms x(t);
ode = diff(x,t) == -1*(1-abs(x)^2*x-(1-0.5)*x);
cond = x(0) == 1;
xSol(t) = dsolve(ode,cond);
t = 0:1:100;
xSols = xSol(t);
plot(t,xSols)Hello,
I wrote the following code to derive an analytical solution to nonlinear equation but it gives an error. Could you please help me to fix it? Or any suggestion to solve in an analytical way. Thanks
syms x(t);
ode = diff(x,t) == -1*(1-abs(x)^2*x-(1-0.5)*x);
cond = x(0) == 1;
xSol(t) = dsolve(ode,cond);
t = 0:1:100;
xSols = xSol(t);
plot(t,xSols)Â Hello,
I wrote the following code to derive an analytical solution to nonlinear equation but it gives an error. Could you please help me to fix it? Or any suggestion to solve in an analytical way. Thanks
syms x(t);
ode = diff(x,t) == -1*(1-abs(x)^2*x-(1-0.5)*x);
cond = x(0) == 1;
xSol(t) = dsolve(ode,cond);
t = 0:1:100;
xSols = xSol(t);
plot(t,xSols) nonlinear MATLAB Answers — New Questions
​
Thingspeak HTTP eror code: -210
We have a project and we have this eror code. We can only send temprature but we need to send more data to thingspeak . We dont know what to do please help us.We have a project and we have this eror code. We can only send temprature but we need to send more data to thingspeak . We dont know what to do please help us. We have a project and we have this eror code. We can only send temprature but we need to send more data to thingspeak . We dont know what to do please help us. thingspeak, esp32s MATLAB Answers — New Questions
​
How to do real Time EEG seizure Detection/analysis?
Hello, I am writing a code that should be able to tell if a signal inputed into the code has a seizure or not. How can I change it so it analyses an eeg recording that may have seizures at some point and then give real time answer/showcases realtime if the current part of the recording has a seizure? I’m not sure where to get started and need some advice if possible.It may need some sort of window but i do not know how to go about it.Hello, I am writing a code that should be able to tell if a signal inputed into the code has a seizure or not. How can I change it so it analyses an eeg recording that may have seizures at some point and then give real time answer/showcases realtime if the current part of the recording has a seizure? I’m not sure where to get started and need some advice if possible.It may need some sort of window but i do not know how to go about it. Hello, I am writing a code that should be able to tell if a signal inputed into the code has a seizure or not. How can I change it so it analyses an eeg recording that may have seizures at some point and then give real time answer/showcases realtime if the current part of the recording has a seizure? I’m not sure where to get started and need some advice if possible.It may need some sort of window but i do not know how to go about it. eeg, real time, matlab code, seizure detection, windowing MATLAB Answers — New Questions
​
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
​
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
​
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
​
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
​
i want matrix E == matrix B(i want correct answer)
I have tried to run this code many times , even changed the equation , values but i am not able to get the correct answer , here A given is before its transpose of glcm
% Convert to grayscale if necessary
%if size(img, 3) > 1
%img = rgb2gray(img);
%end
I = [0 0 1 1;
0 0 1 1;
0 2 2 2;
2 2 3 3];
A = [2 2 1 0;
0 2 0 0;
0 0 3 1;
0 0 0 1];
D = A’;
E = A + D;
E
%glcms = graycomatrix(I);
%glcms
m = 5;
%n = 4;
count = 0;
%count1 = 0;
n = 3;
o = 4;
for i = 1 : 4
for j = 1:4
for l = 1 : 4
for k = 1 : 4
x = I(i,1);
y = I(i,3-1);
a = I(i,3+1-1);
b = I(i,2+2-1);
if (I(i,j) && I(i,n-j)) == (I(i,n-k) && I(i, n+1-k))
%disp(‘Entered the control’);
% count = count+ 1;
%end
end
end
B(i,j) = count;
end
%B(i,j) = count;
%end
%end
end
%if (E == B)
% disp(‘Correct Answer’);
%else
% disp(‘Not Correct Answer’);
%endI have tried to run this code many times , even changed the equation , values but i am not able to get the correct answer , here A given is before its transpose of glcm
% Convert to grayscale if necessary
%if size(img, 3) > 1
%img = rgb2gray(img);
%end
I = [0 0 1 1;
0 0 1 1;
0 2 2 2;
2 2 3 3];
A = [2 2 1 0;
0 2 0 0;
0 0 3 1;
0 0 0 1];
D = A’;
E = A + D;
E
%glcms = graycomatrix(I);
%glcms
m = 5;
%n = 4;
count = 0;
%count1 = 0;
n = 3;
o = 4;
for i = 1 : 4
for j = 1:4
for l = 1 : 4
for k = 1 : 4
x = I(i,1);
y = I(i,3-1);
a = I(i,3+1-1);
b = I(i,2+2-1);
if (I(i,j) && I(i,n-j)) == (I(i,n-k) && I(i, n+1-k))
%disp(‘Entered the control’);
% count = count+ 1;
%end
end
end
B(i,j) = count;
end
%B(i,j) = count;
%end
%end
end
%if (E == B)
% disp(‘Correct Answer’);
%else
% disp(‘Not Correct Answer’);
%end I have tried to run this code many times , even changed the equation , values but i am not able to get the correct answer , here A given is before its transpose of glcm
% Convert to grayscale if necessary
%if size(img, 3) > 1
%img = rgb2gray(img);
%end
I = [0 0 1 1;
0 0 1 1;
0 2 2 2;
2 2 3 3];
A = [2 2 1 0;
0 2 0 0;
0 0 3 1;
0 0 0 1];
D = A’;
E = A + D;
E
%glcms = graycomatrix(I);
%glcms
m = 5;
%n = 4;
count = 0;
%count1 = 0;
n = 3;
o = 4;
for i = 1 : 4
for j = 1:4
for l = 1 : 4
for k = 1 : 4
x = I(i,1);
y = I(i,3-1);
a = I(i,3+1-1);
b = I(i,2+2-1);
if (I(i,j) && I(i,n-j)) == (I(i,n-k) && I(i, n+1-k))
%disp(‘Entered the control’);
% count = count+ 1;
%end
end
end
B(i,j) = count;
end
%B(i,j) = count;
%end
%end
end
%if (E == B)
% disp(‘Correct Answer’);
%else
% disp(‘Not Correct Answer’);
%end glcm MATLAB Answers — New Questions
​
Problem with Section 7.1 Task 5 of Simscape onramp
Although I correctly configured the model blocks and parameters accordingly to the directions, the training evaluation said my output did not match the answer. It prevents me from proceeding to the next task.
Here I attach two snapshots of the evaluation plot of Section 7.1 Task 5 where the problem occured.
The first picture shows comparison of the signals spanning to the end time (10sec). It looks to me exact agreement between the requirement and my signal, but it indicates slight discrepancies in the beginning of simulation (from 0 sec to around 1.0 sec) shown by the red dots. Due to these errors, the evaluator says my signal is incorrect.
The second picture zooms into the details of the red dots. It looks to me my signal has a slight delay to the answer.
I confirmed that my setup is consistent with the directions and the results unchanged even after several retries from the beginning of Section 7.1.
I am wondering if there is another parameter to be adjusted, which is not explicitly directed.
Can I have your help for solving this problem?Although I correctly configured the model blocks and parameters accordingly to the directions, the training evaluation said my output did not match the answer. It prevents me from proceeding to the next task.
Here I attach two snapshots of the evaluation plot of Section 7.1 Task 5 where the problem occured.
The first picture shows comparison of the signals spanning to the end time (10sec). It looks to me exact agreement between the requirement and my signal, but it indicates slight discrepancies in the beginning of simulation (from 0 sec to around 1.0 sec) shown by the red dots. Due to these errors, the evaluator says my signal is incorrect.
The second picture zooms into the details of the red dots. It looks to me my signal has a slight delay to the answer.
I confirmed that my setup is consistent with the directions and the results unchanged even after several retries from the beginning of Section 7.1.
I am wondering if there is another parameter to be adjusted, which is not explicitly directed.
Can I have your help for solving this problem? Although I correctly configured the model blocks and parameters accordingly to the directions, the training evaluation said my output did not match the answer. It prevents me from proceeding to the next task.
Here I attach two snapshots of the evaluation plot of Section 7.1 Task 5 where the problem occured.
The first picture shows comparison of the signals spanning to the end time (10sec). It looks to me exact agreement between the requirement and my signal, but it indicates slight discrepancies in the beginning of simulation (from 0 sec to around 1.0 sec) shown by the red dots. Due to these errors, the evaluator says my signal is incorrect.
The second picture zooms into the details of the red dots. It looks to me my signal has a slight delay to the answer.
I confirmed that my setup is consistent with the directions and the results unchanged even after several retries from the beginning of Section 7.1.
I am wondering if there is another parameter to be adjusted, which is not explicitly directed.
Can I have your help for solving this problem? simscape, onramp MATLAB Answers — New Questions
​