Tag Archives: matlab
How to change the position of reference frame of a body in Simscape?
I have defined a body in Simscape. Moreover, I was able to define a new reference frame named "Position_Right" for the body . This was simple to done as I selected the edge and Simscape automatically defined the reference frame at the mid-point of that edge. However, I want to define the reference frame whose origin should be at the point marked with red. How to do that?
Thanks.I have defined a body in Simscape. Moreover, I was able to define a new reference frame named "Position_Right" for the body . This was simple to done as I selected the edge and Simscape automatically defined the reference frame at the mid-point of that edge. However, I want to define the reference frame whose origin should be at the point marked with red. How to do that?
Thanks. I have defined a body in Simscape. Moreover, I was able to define a new reference frame named "Position_Right" for the body . This was simple to done as I selected the edge and Simscape automatically defined the reference frame at the mid-point of that edge. However, I want to define the reference frame whose origin should be at the point marked with red. How to do that?
Thanks. simscape MATLAB Answers — New Questions
Using fitcdiscr without feature normality
Hi!
I was making a classification task (training a classifier) using fitcdiscr. Is it still possible to use it if my features (the input X) have not a gaussian distribution?
Thanks in advanceHi!
I was making a classification task (training a classifier) using fitcdiscr. Is it still possible to use it if my features (the input X) have not a gaussian distribution?
Thanks in advance Hi!
I was making a classification task (training a classifier) using fitcdiscr. Is it still possible to use it if my features (the input X) have not a gaussian distribution?
Thanks in advance discriminant analysis, machine learning, lda, computer vision MATLAB Answers — New Questions
How to link MATLAB to Aspen Adsorption? But i have Aspen Adsorption linking with Excel VBA code is here
Sub aspenaAdorption()
‘ Declare variables for the ACM application, document, and simulation
Dim ACMApp As Object
Dim ACMDocument As Object
Dim ACMSimulation As Object
‘ Create an instance of the ACM application
Set ACMApp = CreateObject("ACM Application")
‘ Use "ACM Application" for Aspen Custom Modeler
‘ Use "ADS Application" for Aspen Adsorption
‘ Make the ACM application visible
ACMApp.Visible = True
‘ Open the specified simulation document
Set ACMDocument = ACMApp.OpenDocument("C:UsersuserDesktopH2_Purification.acmf")
‘ Set the simulation object to the current simulation in the application
Set ACMSimulation = ACMApp.Simulation
‘ Set the simulation to run in dynamic mode
ACMSimulation.RunMode = "Dynamic"
‘ Run the simulation
ACMSimulation.Run (True)
‘ Check if the simulation was successful and display a message box
If ACMSimulation.Successful Then
MsgBox "Simulation Complete"
Else
MsgBox "Simulation Failed"
End If
‘ Quit the ACM application
ACMApp.Quit
End SubSub aspenaAdorption()
‘ Declare variables for the ACM application, document, and simulation
Dim ACMApp As Object
Dim ACMDocument As Object
Dim ACMSimulation As Object
‘ Create an instance of the ACM application
Set ACMApp = CreateObject("ACM Application")
‘ Use "ACM Application" for Aspen Custom Modeler
‘ Use "ADS Application" for Aspen Adsorption
‘ Make the ACM application visible
ACMApp.Visible = True
‘ Open the specified simulation document
Set ACMDocument = ACMApp.OpenDocument("C:UsersuserDesktopH2_Purification.acmf")
‘ Set the simulation object to the current simulation in the application
Set ACMSimulation = ACMApp.Simulation
‘ Set the simulation to run in dynamic mode
ACMSimulation.RunMode = "Dynamic"
‘ Run the simulation
ACMSimulation.Run (True)
‘ Check if the simulation was successful and display a message box
If ACMSimulation.Successful Then
MsgBox "Simulation Complete"
Else
MsgBox "Simulation Failed"
End If
‘ Quit the ACM application
ACMApp.Quit
End Sub Sub aspenaAdorption()
‘ Declare variables for the ACM application, document, and simulation
Dim ACMApp As Object
Dim ACMDocument As Object
Dim ACMSimulation As Object
‘ Create an instance of the ACM application
Set ACMApp = CreateObject("ACM Application")
‘ Use "ACM Application" for Aspen Custom Modeler
‘ Use "ADS Application" for Aspen Adsorption
‘ Make the ACM application visible
ACMApp.Visible = True
‘ Open the specified simulation document
Set ACMDocument = ACMApp.OpenDocument("C:UsersuserDesktopH2_Purification.acmf")
‘ Set the simulation object to the current simulation in the application
Set ACMSimulation = ACMApp.Simulation
‘ Set the simulation to run in dynamic mode
ACMSimulation.RunMode = "Dynamic"
‘ Run the simulation
ACMSimulation.Run (True)
‘ Check if the simulation was successful and display a message box
If ACMSimulation.Successful Then
MsgBox "Simulation Complete"
Else
MsgBox "Simulation Failed"
End If
‘ Quit the ACM application
ACMApp.Quit
End Sub aspenadsorption, aspen, aspen adsorption link, aspen matlab MATLAB Answers — New Questions
here i need to calculate the BER of UAV based fso system using lognormal model.but after writing the code, i got BER is increasing wrt pt. can anyone suggest me where i got the mistake ?
clear; close all; clc;
%% Define constants and variables
% FSO Parameters
q = 1.602e-19; % Charge of electron
F = 2.75; % Excess noise factor of APD
ra = 10; % Receiver lens radius in cm
wz = 400; % Receiver beam width in cm
sigma_R = 0.2; % Rytov variance for weak turbulence modeled by LN
lambda = 1550e-9; % Optical wavelength
h_planck = 6.626e-34; % Planck’s constant in m^2-kg/s
k_boltz = 1.38064852e-23; % Boltzmann constant in W/K
c = 3e8; % Speed of light
O_f = c / lambda; % Optical frequency
Mew = 0.8; % APD quantum efficiency
G = 30; % Average APD Gain
Be = 1e9; % Electrical bandwidth
Bo = 1e-9; % Optical filter bandwidth
Nb = 1e-3; % Spectral radiance of background radiation
Rl = 1e3; % Receiver Load Resistance
Tr = 300; % Receiver Temperature
Rb = 1; % Data rate in Gbps
Z = 500; % Link length in meters
theta_FOV = 40e-3; % Field of view variations in radians
Pt_dBm = -10:2:50; % Transmit power in dBm
pt = (10^-3) * 10.^(Pt_dBm / 10); % Transmit power in linear scale
eta = (q * G * Mew) / (h_planck * O_f);
Pb = 0.25 * ra^2 * Bo * Nb * theta_FOV^2; % Background power
sigma_th = (4 * k_boltz * Tr * Be) / Rl; % variance of thermal noise
sigma_b = 2 * q * G * F * Be * eta * Pb; % noise variance due to background radiation
% UAV Parameters
sigma_to = 1e-3; % Standard deviation of orientation fluctuation of Tx in radians
sigma_ro = 1e-3; % Standard deviation of orientation fluctuation of Rx in radians
sigma_tp = 40; % Standard deviation of position fluctuation of Tx in centimeters
sigma_rp = 40; % Standard deviation of position fluctuation of Rx in centimeters
% Channel Coefficient Formulas Calculation
hl_dB = 10; % Channel loss in dB
hl = 10^(hl_dB / 10);
v = sqrt(pi / 2) * (ra / wz);
wz_eq = wz^2 * ((sqrt(pi) * erf(v)) / (2 * v * exp(-v^2)));
Ao = (erf(v))^2;
T_base = (wz_eq) / (4 * ((Z * sigma_to)^2 + sigma_tp^2 + sigma_rp^2));
C1 = (T_base / ((Ao * hl)^T_base)) * exp(0.5 * sigma_R * T_base * (1 + T_base));
C2 = T_base – 1;
C3 = 0.5 * sigma_R * (1 + 2 * T_base);
a = [5/24, 4/24, 1/24];
ai_prime = [2, 11/20, 1/2];
M = 2;
% Preallocate Pe array
Pe = zeros(size(Pt_dBm));
% Calculate h1 and b1
h1 = Ao * hl * exp(-C3);
% Loop over different transmit powers
for idx = 1:length(pt)
current_pt = pt(idx);
b1 = eta * current_pt / sqrt(8 * (sigma_th^2 + sigma_b^2));
% Initialize Pe for current pt
Pe(idx) = 0;
% First part of the equation
Pe(idx) = Pe(idx) + 0.5 * exp(-theta_FOV^2 / (2 * (sigma_to^2 + sigma_ro^2)));
% Second part of the equation
sum_term1 = 0;
for i = 1:3
term1 = (a(i) * h1^(C2 + 1)) / 2;
term2 = (1 / (C2 + 1))+sqrt((sigma_R * pi) / ai_prime(i)) * exp((sigma_R * (C2 + 1)^2) / (4 * ai_prime(i))) * …
erf((sqrt(sigma_R) * (C2 + 1)) / (2 * sqrt(ai_prime(i))));
sum_term2 = 0; % Initialize sum_term2 for each i
for m = 0:M
term3 = (2 / sqrt(pi)) * ((-1)^m * (b1 * h1)^(2 * m + 1) / (factorial(m) * (2 * m + 1)));
term4 = (-1) / (C2 + 2 * m + 2);
term5 = sqrt((sigma_R*pi) / ai_prime(i)) * exp((sigma_R * (C2 + 2 * m + 2)^2 )/ (4 * ai_prime(i))) * …
erf((sqrt(sigma_R) * (C2 + 2 * m + 2)) / (2 * sqrt(ai_prime(i))));
sum_term2 = sum_term2 + term3 * (term4 + term5);
end
sum_term1 = sum_term1 + term1 * (term2 + sum_term2);
end
Pe(idx) = Pe(idx) + C1 * (1 – exp(-theta_FOV^2 / (2 * (sigma_to^2 + sigma_ro^2)))) * sum_term1;
end
% Normalize the BER values to decrease from 10^0
Pe = Pe / max(Pe);
% Plot Pt_dBm versus normalized BER
figure;
semilogy(Pt_dBm, Pe, ‘o-‘, ‘LineWidth’, 2);
xlabel(‘Transmit Power (dBm)’);
ylabel(‘Normalized Bit Error Rate (BER)’);
title(‘Transmit Power vs. Normalized BER’);
grid on;clear; close all; clc;
%% Define constants and variables
% FSO Parameters
q = 1.602e-19; % Charge of electron
F = 2.75; % Excess noise factor of APD
ra = 10; % Receiver lens radius in cm
wz = 400; % Receiver beam width in cm
sigma_R = 0.2; % Rytov variance for weak turbulence modeled by LN
lambda = 1550e-9; % Optical wavelength
h_planck = 6.626e-34; % Planck’s constant in m^2-kg/s
k_boltz = 1.38064852e-23; % Boltzmann constant in W/K
c = 3e8; % Speed of light
O_f = c / lambda; % Optical frequency
Mew = 0.8; % APD quantum efficiency
G = 30; % Average APD Gain
Be = 1e9; % Electrical bandwidth
Bo = 1e-9; % Optical filter bandwidth
Nb = 1e-3; % Spectral radiance of background radiation
Rl = 1e3; % Receiver Load Resistance
Tr = 300; % Receiver Temperature
Rb = 1; % Data rate in Gbps
Z = 500; % Link length in meters
theta_FOV = 40e-3; % Field of view variations in radians
Pt_dBm = -10:2:50; % Transmit power in dBm
pt = (10^-3) * 10.^(Pt_dBm / 10); % Transmit power in linear scale
eta = (q * G * Mew) / (h_planck * O_f);
Pb = 0.25 * ra^2 * Bo * Nb * theta_FOV^2; % Background power
sigma_th = (4 * k_boltz * Tr * Be) / Rl; % variance of thermal noise
sigma_b = 2 * q * G * F * Be * eta * Pb; % noise variance due to background radiation
% UAV Parameters
sigma_to = 1e-3; % Standard deviation of orientation fluctuation of Tx in radians
sigma_ro = 1e-3; % Standard deviation of orientation fluctuation of Rx in radians
sigma_tp = 40; % Standard deviation of position fluctuation of Tx in centimeters
sigma_rp = 40; % Standard deviation of position fluctuation of Rx in centimeters
% Channel Coefficient Formulas Calculation
hl_dB = 10; % Channel loss in dB
hl = 10^(hl_dB / 10);
v = sqrt(pi / 2) * (ra / wz);
wz_eq = wz^2 * ((sqrt(pi) * erf(v)) / (2 * v * exp(-v^2)));
Ao = (erf(v))^2;
T_base = (wz_eq) / (4 * ((Z * sigma_to)^2 + sigma_tp^2 + sigma_rp^2));
C1 = (T_base / ((Ao * hl)^T_base)) * exp(0.5 * sigma_R * T_base * (1 + T_base));
C2 = T_base – 1;
C3 = 0.5 * sigma_R * (1 + 2 * T_base);
a = [5/24, 4/24, 1/24];
ai_prime = [2, 11/20, 1/2];
M = 2;
% Preallocate Pe array
Pe = zeros(size(Pt_dBm));
% Calculate h1 and b1
h1 = Ao * hl * exp(-C3);
% Loop over different transmit powers
for idx = 1:length(pt)
current_pt = pt(idx);
b1 = eta * current_pt / sqrt(8 * (sigma_th^2 + sigma_b^2));
% Initialize Pe for current pt
Pe(idx) = 0;
% First part of the equation
Pe(idx) = Pe(idx) + 0.5 * exp(-theta_FOV^2 / (2 * (sigma_to^2 + sigma_ro^2)));
% Second part of the equation
sum_term1 = 0;
for i = 1:3
term1 = (a(i) * h1^(C2 + 1)) / 2;
term2 = (1 / (C2 + 1))+sqrt((sigma_R * pi) / ai_prime(i)) * exp((sigma_R * (C2 + 1)^2) / (4 * ai_prime(i))) * …
erf((sqrt(sigma_R) * (C2 + 1)) / (2 * sqrt(ai_prime(i))));
sum_term2 = 0; % Initialize sum_term2 for each i
for m = 0:M
term3 = (2 / sqrt(pi)) * ((-1)^m * (b1 * h1)^(2 * m + 1) / (factorial(m) * (2 * m + 1)));
term4 = (-1) / (C2 + 2 * m + 2);
term5 = sqrt((sigma_R*pi) / ai_prime(i)) * exp((sigma_R * (C2 + 2 * m + 2)^2 )/ (4 * ai_prime(i))) * …
erf((sqrt(sigma_R) * (C2 + 2 * m + 2)) / (2 * sqrt(ai_prime(i))));
sum_term2 = sum_term2 + term3 * (term4 + term5);
end
sum_term1 = sum_term1 + term1 * (term2 + sum_term2);
end
Pe(idx) = Pe(idx) + C1 * (1 – exp(-theta_FOV^2 / (2 * (sigma_to^2 + sigma_ro^2)))) * sum_term1;
end
% Normalize the BER values to decrease from 10^0
Pe = Pe / max(Pe);
% Plot Pt_dBm versus normalized BER
figure;
semilogy(Pt_dBm, Pe, ‘o-‘, ‘LineWidth’, 2);
xlabel(‘Transmit Power (dBm)’);
ylabel(‘Normalized Bit Error Rate (BER)’);
title(‘Transmit Power vs. Normalized BER’);
grid on; clear; close all; clc;
%% Define constants and variables
% FSO Parameters
q = 1.602e-19; % Charge of electron
F = 2.75; % Excess noise factor of APD
ra = 10; % Receiver lens radius in cm
wz = 400; % Receiver beam width in cm
sigma_R = 0.2; % Rytov variance for weak turbulence modeled by LN
lambda = 1550e-9; % Optical wavelength
h_planck = 6.626e-34; % Planck’s constant in m^2-kg/s
k_boltz = 1.38064852e-23; % Boltzmann constant in W/K
c = 3e8; % Speed of light
O_f = c / lambda; % Optical frequency
Mew = 0.8; % APD quantum efficiency
G = 30; % Average APD Gain
Be = 1e9; % Electrical bandwidth
Bo = 1e-9; % Optical filter bandwidth
Nb = 1e-3; % Spectral radiance of background radiation
Rl = 1e3; % Receiver Load Resistance
Tr = 300; % Receiver Temperature
Rb = 1; % Data rate in Gbps
Z = 500; % Link length in meters
theta_FOV = 40e-3; % Field of view variations in radians
Pt_dBm = -10:2:50; % Transmit power in dBm
pt = (10^-3) * 10.^(Pt_dBm / 10); % Transmit power in linear scale
eta = (q * G * Mew) / (h_planck * O_f);
Pb = 0.25 * ra^2 * Bo * Nb * theta_FOV^2; % Background power
sigma_th = (4 * k_boltz * Tr * Be) / Rl; % variance of thermal noise
sigma_b = 2 * q * G * F * Be * eta * Pb; % noise variance due to background radiation
% UAV Parameters
sigma_to = 1e-3; % Standard deviation of orientation fluctuation of Tx in radians
sigma_ro = 1e-3; % Standard deviation of orientation fluctuation of Rx in radians
sigma_tp = 40; % Standard deviation of position fluctuation of Tx in centimeters
sigma_rp = 40; % Standard deviation of position fluctuation of Rx in centimeters
% Channel Coefficient Formulas Calculation
hl_dB = 10; % Channel loss in dB
hl = 10^(hl_dB / 10);
v = sqrt(pi / 2) * (ra / wz);
wz_eq = wz^2 * ((sqrt(pi) * erf(v)) / (2 * v * exp(-v^2)));
Ao = (erf(v))^2;
T_base = (wz_eq) / (4 * ((Z * sigma_to)^2 + sigma_tp^2 + sigma_rp^2));
C1 = (T_base / ((Ao * hl)^T_base)) * exp(0.5 * sigma_R * T_base * (1 + T_base));
C2 = T_base – 1;
C3 = 0.5 * sigma_R * (1 + 2 * T_base);
a = [5/24, 4/24, 1/24];
ai_prime = [2, 11/20, 1/2];
M = 2;
% Preallocate Pe array
Pe = zeros(size(Pt_dBm));
% Calculate h1 and b1
h1 = Ao * hl * exp(-C3);
% Loop over different transmit powers
for idx = 1:length(pt)
current_pt = pt(idx);
b1 = eta * current_pt / sqrt(8 * (sigma_th^2 + sigma_b^2));
% Initialize Pe for current pt
Pe(idx) = 0;
% First part of the equation
Pe(idx) = Pe(idx) + 0.5 * exp(-theta_FOV^2 / (2 * (sigma_to^2 + sigma_ro^2)));
% Second part of the equation
sum_term1 = 0;
for i = 1:3
term1 = (a(i) * h1^(C2 + 1)) / 2;
term2 = (1 / (C2 + 1))+sqrt((sigma_R * pi) / ai_prime(i)) * exp((sigma_R * (C2 + 1)^2) / (4 * ai_prime(i))) * …
erf((sqrt(sigma_R) * (C2 + 1)) / (2 * sqrt(ai_prime(i))));
sum_term2 = 0; % Initialize sum_term2 for each i
for m = 0:M
term3 = (2 / sqrt(pi)) * ((-1)^m * (b1 * h1)^(2 * m + 1) / (factorial(m) * (2 * m + 1)));
term4 = (-1) / (C2 + 2 * m + 2);
term5 = sqrt((sigma_R*pi) / ai_prime(i)) * exp((sigma_R * (C2 + 2 * m + 2)^2 )/ (4 * ai_prime(i))) * …
erf((sqrt(sigma_R) * (C2 + 2 * m + 2)) / (2 * sqrt(ai_prime(i))));
sum_term2 = sum_term2 + term3 * (term4 + term5);
end
sum_term1 = sum_term1 + term1 * (term2 + sum_term2);
end
Pe(idx) = Pe(idx) + C1 * (1 – exp(-theta_FOV^2 / (2 * (sigma_to^2 + sigma_ro^2)))) * sum_term1;
end
% Normalize the BER values to decrease from 10^0
Pe = Pe / max(Pe);
% Plot Pt_dBm versus normalized BER
figure;
semilogy(Pt_dBm, Pe, ‘o-‘, ‘LineWidth’, 2);
xlabel(‘Transmit Power (dBm)’);
ylabel(‘Normalized Bit Error Rate (BER)’);
title(‘Transmit Power vs. Normalized BER’);
grid on; transferred MATLAB Answers — New Questions
DDPG does not converge
Hello
I am using a DDPG agent that generates 4 continuous actions (2 positive values- 2negative values). The summation of 2 positive action values must be equal to the positive part of a reference value, and the summation of 2 negative action values must be equal to the negative part of the reference value. However, the agent can’t learn to track the reference. I have tried different reward functions and hyperparameters, but after a while it always chooses the maximum values of defined action ranges ([-1 -1 1 1]).
Any suggestion I appreciate
open_system(mdl)
obsInfo = rlNumericSpec([2 1]);
obsInfo.Name = ‘observations’;
numObservations = obsInfo.Dimension(1);
actInfo = rlNumericSpec([4 1],…
LowerLimit=[-1 -1 0 0]’,…
UpperLimit=[0 0 1 1]’);
numActions = actInfo.Dimension(1);
%Build the environment interface object
agentblk = ‘MEMG_RL/RL Agent’;
env = rlSimulinkEnv(mdl,agentblk,obsInfo,actInfo);
Ts = 2e-2;
Tf = 60;
statepath = [featureInputLayer(numObservations , Name = ‘stateinp’)
fullyConnectedLayer(96,Name = ‘stateFC1’)
reluLayer
fullyConnectedLayer(74,Name = ‘stateFC2’)
reluLayer
fullyConnectedLayer(36,Name = ‘stateFC3’)];
actionpath = [featureInputLayer(numActions, Name = ‘actinp’)
fullyConnectedLayer(72,Name = ‘actFC1’)
reluLayer
fullyConnectedLayer(36,Name = ‘actFC2’)];
commonpath = [additionLayer(2,Name = ‘add’)
fullyConnectedLayer(96,Name = ‘FC1’)
reluLayer
fullyConnectedLayer(72,Name = ‘FC2’)
reluLayer
fullyConnectedLayer(24,Name = ‘FC3’)
reluLayer
fullyConnectedLayer(1,Name = ‘output’)];
critic_network = layerGraph();
critic_network = addLayers(critic_network,actionpath);
critic_network = addLayers(critic_network,statepath);
critic_network = addLayers(critic_network,commonpath);
critic_network = connectLayers(critic_network,’actFC2′,’add/in1′);
critic_network = connectLayers(critic_network,’stateFC3′,’add/in2′);
plot(critic_network)
critic = dlnetwork(critic_network);
criticOptions = rlOptimizerOptions(‘LearnRate’,3e-04,’GradientThreshold’,1);
critic = rlQValueFunction(critic,obsInfo,actInfo,…
‘ObservationInputNames’,’stateinp’,’ActionInputNames’,’actinp’);
%% actor
actorNetwork = [featureInputLayer(numObservations,Name = ‘observation’)
fullyConnectedLayer(72,Name = ‘actorFC1’)
reluLayer
fullyConnectedLayer(48,Name=’actorFc2′)
reluLayer
fullyConnectedLayer(36,Name=’actorFc3′)
reluLayer
fullyConnectedLayer(numActions,Name=’output’)
tanhLayer
scalingLayer(Name = ‘actorscaling’,scale = max(actInfo.UpperLimit))];
actorNetwork = dlnetwork(actorNetwork);
actorOptions = rlOptimizerOptions(‘LearnRate’,3e-04,’GradientThreshold’,1);
actor = rlContinuousDeterministicActor(actorNetwork,obsInfo,actInfo);
%% agent
agentOptions = rlDDPGAgentOptions(…
‘SampleTime’,Ts,…
‘ActorOptimizerOptions’,actorOptions,…
‘CriticOptimizerOptions’,criticOptions,…
‘ExperienceBufferLength’,1e6,…
‘MiniBatchSize’,128);
agentOptions.NoiseOptions.StandardDeviation = 0.1; %.07/sqrt(Ts) ;
agentOptions.NoiseOptions.StandardDeviationDecayRate = 1e-6;
maxepisodes = 5000;
maxsteps = ceil(Tf/Ts);
trainOpts = rlTrainingOptions(…
‘MaxEpisodes’,maxepisodes, …
‘MaxStepsPerEpisode’,maxsteps, …
‘ScoreAveragingWindowLength’,20, …
‘Verbose’,false, …
‘Plots’,’training-progress’,…
‘StopTrainingCriteria’,’EpisodeCount’,…
‘StopTrainingValue’,5000);
agent = rlDDPGAgent(actor,critic,agentOptions);Hello
I am using a DDPG agent that generates 4 continuous actions (2 positive values- 2negative values). The summation of 2 positive action values must be equal to the positive part of a reference value, and the summation of 2 negative action values must be equal to the negative part of the reference value. However, the agent can’t learn to track the reference. I have tried different reward functions and hyperparameters, but after a while it always chooses the maximum values of defined action ranges ([-1 -1 1 1]).
Any suggestion I appreciate
open_system(mdl)
obsInfo = rlNumericSpec([2 1]);
obsInfo.Name = ‘observations’;
numObservations = obsInfo.Dimension(1);
actInfo = rlNumericSpec([4 1],…
LowerLimit=[-1 -1 0 0]’,…
UpperLimit=[0 0 1 1]’);
numActions = actInfo.Dimension(1);
%Build the environment interface object
agentblk = ‘MEMG_RL/RL Agent’;
env = rlSimulinkEnv(mdl,agentblk,obsInfo,actInfo);
Ts = 2e-2;
Tf = 60;
statepath = [featureInputLayer(numObservations , Name = ‘stateinp’)
fullyConnectedLayer(96,Name = ‘stateFC1’)
reluLayer
fullyConnectedLayer(74,Name = ‘stateFC2’)
reluLayer
fullyConnectedLayer(36,Name = ‘stateFC3’)];
actionpath = [featureInputLayer(numActions, Name = ‘actinp’)
fullyConnectedLayer(72,Name = ‘actFC1’)
reluLayer
fullyConnectedLayer(36,Name = ‘actFC2’)];
commonpath = [additionLayer(2,Name = ‘add’)
fullyConnectedLayer(96,Name = ‘FC1’)
reluLayer
fullyConnectedLayer(72,Name = ‘FC2’)
reluLayer
fullyConnectedLayer(24,Name = ‘FC3’)
reluLayer
fullyConnectedLayer(1,Name = ‘output’)];
critic_network = layerGraph();
critic_network = addLayers(critic_network,actionpath);
critic_network = addLayers(critic_network,statepath);
critic_network = addLayers(critic_network,commonpath);
critic_network = connectLayers(critic_network,’actFC2′,’add/in1′);
critic_network = connectLayers(critic_network,’stateFC3′,’add/in2′);
plot(critic_network)
critic = dlnetwork(critic_network);
criticOptions = rlOptimizerOptions(‘LearnRate’,3e-04,’GradientThreshold’,1);
critic = rlQValueFunction(critic,obsInfo,actInfo,…
‘ObservationInputNames’,’stateinp’,’ActionInputNames’,’actinp’);
%% actor
actorNetwork = [featureInputLayer(numObservations,Name = ‘observation’)
fullyConnectedLayer(72,Name = ‘actorFC1’)
reluLayer
fullyConnectedLayer(48,Name=’actorFc2′)
reluLayer
fullyConnectedLayer(36,Name=’actorFc3′)
reluLayer
fullyConnectedLayer(numActions,Name=’output’)
tanhLayer
scalingLayer(Name = ‘actorscaling’,scale = max(actInfo.UpperLimit))];
actorNetwork = dlnetwork(actorNetwork);
actorOptions = rlOptimizerOptions(‘LearnRate’,3e-04,’GradientThreshold’,1);
actor = rlContinuousDeterministicActor(actorNetwork,obsInfo,actInfo);
%% agent
agentOptions = rlDDPGAgentOptions(…
‘SampleTime’,Ts,…
‘ActorOptimizerOptions’,actorOptions,…
‘CriticOptimizerOptions’,criticOptions,…
‘ExperienceBufferLength’,1e6,…
‘MiniBatchSize’,128);
agentOptions.NoiseOptions.StandardDeviation = 0.1; %.07/sqrt(Ts) ;
agentOptions.NoiseOptions.StandardDeviationDecayRate = 1e-6;
maxepisodes = 5000;
maxsteps = ceil(Tf/Ts);
trainOpts = rlTrainingOptions(…
‘MaxEpisodes’,maxepisodes, …
‘MaxStepsPerEpisode’,maxsteps, …
‘ScoreAveragingWindowLength’,20, …
‘Verbose’,false, …
‘Plots’,’training-progress’,…
‘StopTrainingCriteria’,’EpisodeCount’,…
‘StopTrainingValue’,5000);
agent = rlDDPGAgent(actor,critic,agentOptions); Hello
I am using a DDPG agent that generates 4 continuous actions (2 positive values- 2negative values). The summation of 2 positive action values must be equal to the positive part of a reference value, and the summation of 2 negative action values must be equal to the negative part of the reference value. However, the agent can’t learn to track the reference. I have tried different reward functions and hyperparameters, but after a while it always chooses the maximum values of defined action ranges ([-1 -1 1 1]).
Any suggestion I appreciate
open_system(mdl)
obsInfo = rlNumericSpec([2 1]);
obsInfo.Name = ‘observations’;
numObservations = obsInfo.Dimension(1);
actInfo = rlNumericSpec([4 1],…
LowerLimit=[-1 -1 0 0]’,…
UpperLimit=[0 0 1 1]’);
numActions = actInfo.Dimension(1);
%Build the environment interface object
agentblk = ‘MEMG_RL/RL Agent’;
env = rlSimulinkEnv(mdl,agentblk,obsInfo,actInfo);
Ts = 2e-2;
Tf = 60;
statepath = [featureInputLayer(numObservations , Name = ‘stateinp’)
fullyConnectedLayer(96,Name = ‘stateFC1’)
reluLayer
fullyConnectedLayer(74,Name = ‘stateFC2’)
reluLayer
fullyConnectedLayer(36,Name = ‘stateFC3’)];
actionpath = [featureInputLayer(numActions, Name = ‘actinp’)
fullyConnectedLayer(72,Name = ‘actFC1’)
reluLayer
fullyConnectedLayer(36,Name = ‘actFC2’)];
commonpath = [additionLayer(2,Name = ‘add’)
fullyConnectedLayer(96,Name = ‘FC1’)
reluLayer
fullyConnectedLayer(72,Name = ‘FC2’)
reluLayer
fullyConnectedLayer(24,Name = ‘FC3’)
reluLayer
fullyConnectedLayer(1,Name = ‘output’)];
critic_network = layerGraph();
critic_network = addLayers(critic_network,actionpath);
critic_network = addLayers(critic_network,statepath);
critic_network = addLayers(critic_network,commonpath);
critic_network = connectLayers(critic_network,’actFC2′,’add/in1′);
critic_network = connectLayers(critic_network,’stateFC3′,’add/in2′);
plot(critic_network)
critic = dlnetwork(critic_network);
criticOptions = rlOptimizerOptions(‘LearnRate’,3e-04,’GradientThreshold’,1);
critic = rlQValueFunction(critic,obsInfo,actInfo,…
‘ObservationInputNames’,’stateinp’,’ActionInputNames’,’actinp’);
%% actor
actorNetwork = [featureInputLayer(numObservations,Name = ‘observation’)
fullyConnectedLayer(72,Name = ‘actorFC1’)
reluLayer
fullyConnectedLayer(48,Name=’actorFc2′)
reluLayer
fullyConnectedLayer(36,Name=’actorFc3′)
reluLayer
fullyConnectedLayer(numActions,Name=’output’)
tanhLayer
scalingLayer(Name = ‘actorscaling’,scale = max(actInfo.UpperLimit))];
actorNetwork = dlnetwork(actorNetwork);
actorOptions = rlOptimizerOptions(‘LearnRate’,3e-04,’GradientThreshold’,1);
actor = rlContinuousDeterministicActor(actorNetwork,obsInfo,actInfo);
%% agent
agentOptions = rlDDPGAgentOptions(…
‘SampleTime’,Ts,…
‘ActorOptimizerOptions’,actorOptions,…
‘CriticOptimizerOptions’,criticOptions,…
‘ExperienceBufferLength’,1e6,…
‘MiniBatchSize’,128);
agentOptions.NoiseOptions.StandardDeviation = 0.1; %.07/sqrt(Ts) ;
agentOptions.NoiseOptions.StandardDeviationDecayRate = 1e-6;
maxepisodes = 5000;
maxsteps = ceil(Tf/Ts);
trainOpts = rlTrainingOptions(…
‘MaxEpisodes’,maxepisodes, …
‘MaxStepsPerEpisode’,maxsteps, …
‘ScoreAveragingWindowLength’,20, …
‘Verbose’,false, …
‘Plots’,’training-progress’,…
‘StopTrainingCriteria’,’EpisodeCount’,…
‘StopTrainingValue’,5000);
agent = rlDDPGAgent(actor,critic,agentOptions); ddpg, converg MATLAB Answers — New Questions
Add “Block Parametrization Manager” to custom ssc block for Simscape
For Simscape, I build a custom block "Vacuum pump" for the gas network. I have data from different suppliers and would like to select the data using the "Block Parametrization Manager" (see e.g. block "Centrifugal Pump (IL)").
Is it possible to add the "Block Parametrization Manager" to my custom block. If yes, what is the command-line to add in my ssc file.For Simscape, I build a custom block "Vacuum pump" for the gas network. I have data from different suppliers and would like to select the data using the "Block Parametrization Manager" (see e.g. block "Centrifugal Pump (IL)").
Is it possible to add the "Block Parametrization Manager" to my custom block. If yes, what is the command-line to add in my ssc file. For Simscape, I build a custom block "Vacuum pump" for the gas network. I have data from different suppliers and would like to select the data using the "Block Parametrization Manager" (see e.g. block "Centrifugal Pump (IL)").
Is it possible to add the "Block Parametrization Manager" to my custom block. If yes, what is the command-line to add in my ssc file. simscape MATLAB Answers — New Questions
Efficiency of “quadprog” in MATLAB
I need to use a QP solver for an NMPC (with SQP) scheme I am writing in MATLAB.
I am mostly writing everything from scratch, both to learn more about NMPC, and to have more control over the implementation when doing research. However, I don’t really feel the need to write my own QP solver, which would probably me way less effecient than modern solvers.
Initially i figured I’d just use quadprog for simplicity, but my supervisor says that this used to be a notoriously slow solver back in the day. I was wondering if this is still the case, or if it has been improved and can compare with other solvers today?
Also, what solvers are fairly efficient and are easy to obtain and use from MATLAB? (as alternatives to quadprog, if it does don’t perform well enough)I need to use a QP solver for an NMPC (with SQP) scheme I am writing in MATLAB.
I am mostly writing everything from scratch, both to learn more about NMPC, and to have more control over the implementation when doing research. However, I don’t really feel the need to write my own QP solver, which would probably me way less effecient than modern solvers.
Initially i figured I’d just use quadprog for simplicity, but my supervisor says that this used to be a notoriously slow solver back in the day. I was wondering if this is still the case, or if it has been improved and can compare with other solvers today?
Also, what solvers are fairly efficient and are easy to obtain and use from MATLAB? (as alternatives to quadprog, if it does don’t perform well enough) I need to use a QP solver for an NMPC (with SQP) scheme I am writing in MATLAB.
I am mostly writing everything from scratch, both to learn more about NMPC, and to have more control over the implementation when doing research. However, I don’t really feel the need to write my own QP solver, which would probably me way less effecient than modern solvers.
Initially i figured I’d just use quadprog for simplicity, but my supervisor says that this used to be a notoriously slow solver back in the day. I was wondering if this is still the case, or if it has been improved and can compare with other solvers today?
Also, what solvers are fairly efficient and are easy to obtain and use from MATLAB? (as alternatives to quadprog, if it does don’t perform well enough) quadprog, qp, efficiency, mpc, sqp MATLAB Answers — New Questions
How to calculate PSD estimate of acoustic data in 1Hz bins? pwelch?
Hi everyone,
I have several files of 118.5 second duration that I would like to calculate the PSD of. I want to do this in 1Hz frequency bins, with Hanning window and 50% overlap, and have considered using pwelch.
First I calibrate the data and then have tried to work out how to use pwelch to no avail so far:
path=(‘C:Usersdatafolder’);
d=dir(fullfile(path, ‘*.wav’)); %list all .wav files in path folder
files=length(d); %number of files in folder
for i=1:files %for each file
disp(d(i).name);
filename=fullfile(path, d(i).name); %get full filename
[xbit, fs]=audioread(filename); %and then sampled data and sampling
%freq (fs) from audioread function
cal=-176.2;
cal=power(10, cal/20); %calibration correction factor
calxbit=xbit*cal; %apply calibration
end
[pxx,f]=pwelch(calxbit, window, 0.5, [], 144e3);
How do I specify that I want to use 1Hz bins? My data is sampled at 144kHz.
Thanks!!Hi everyone,
I have several files of 118.5 second duration that I would like to calculate the PSD of. I want to do this in 1Hz frequency bins, with Hanning window and 50% overlap, and have considered using pwelch.
First I calibrate the data and then have tried to work out how to use pwelch to no avail so far:
path=(‘C:Usersdatafolder’);
d=dir(fullfile(path, ‘*.wav’)); %list all .wav files in path folder
files=length(d); %number of files in folder
for i=1:files %for each file
disp(d(i).name);
filename=fullfile(path, d(i).name); %get full filename
[xbit, fs]=audioread(filename); %and then sampled data and sampling
%freq (fs) from audioread function
cal=-176.2;
cal=power(10, cal/20); %calibration correction factor
calxbit=xbit*cal; %apply calibration
end
[pxx,f]=pwelch(calxbit, window, 0.5, [], 144e3);
How do I specify that I want to use 1Hz bins? My data is sampled at 144kHz.
Thanks!! Hi everyone,
I have several files of 118.5 second duration that I would like to calculate the PSD of. I want to do this in 1Hz frequency bins, with Hanning window and 50% overlap, and have considered using pwelch.
First I calibrate the data and then have tried to work out how to use pwelch to no avail so far:
path=(‘C:Usersdatafolder’);
d=dir(fullfile(path, ‘*.wav’)); %list all .wav files in path folder
files=length(d); %number of files in folder
for i=1:files %for each file
disp(d(i).name);
filename=fullfile(path, d(i).name); %get full filename
[xbit, fs]=audioread(filename); %and then sampled data and sampling
%freq (fs) from audioread function
cal=-176.2;
cal=power(10, cal/20); %calibration correction factor
calxbit=xbit*cal; %apply calibration
end
[pxx,f]=pwelch(calxbit, window, 0.5, [], 144e3);
How do I specify that I want to use 1Hz bins? My data is sampled at 144kHz.
Thanks!! power spectral density, acoustics, soundscape MATLAB Answers — New Questions
fzero of MATLAB and FindRoot of Mathematica give different results
Dear all, I am writing a small script to solve the temperature dependence of magnetization using a toy model. Mathematically, the problem is to determine the relation between reduced magnetization and reduced temperature . The equation is given by , where is the Brillouin function.
To solve this problem, I transform it into a root-finding problem, specifically . I used MATLAB’s fzero and Mathematica’s FindRoot to solve this equation. However, I noticed that the results from the two methods are not consistent. The result from Mathematica matches the reference, while the MATLAB result also appears reasonable. In both cases, as a function of tends to zero from two different directions as increases.
Is this correct? Could you please comment or share your opinions on this matter?
Here is the MATLAB code:
clearvars; clc; close all; fclose all; format compact; format short;
B = @(J, x) ((2*J+1)/(2*J))*coth(((2*J+1)/(2*J))*x)-(1/(2*J)).*coth((1/(2*J))*x);
J = 1/2;
n = 101;
tau_array = linspace(0, 1.2, n);
m_array = zeros(1, n);
for i = 1:n
tau = tau_array(i);
fun = @(m) B(J, ((3*J)/(J+1))*m*(1/tau)) – m;
x = fzero(fun,[-1, 1]);
m_array(i) = x;
end
fig = figure();
ax = axes(fig);
plot(ax, tau_array, m_array,"LineWidth",2,"Color","red");
xlabel(‘Reudced temperature, tau’);
ylabel(‘Redueced magnetization, m’)
title(‘m as a function of tau’)
ax.TickDir = ‘out’;
Here is the Mathematica code:
Here is the reference result, which is taken from this paper [DOI: 10.1109/ISSE.2008.5276604; https://ieeexplore.ieee.org/document/5276604](See Equation 20 and Figure 3)
Thank you.Dear all, I am writing a small script to solve the temperature dependence of magnetization using a toy model. Mathematically, the problem is to determine the relation between reduced magnetization and reduced temperature . The equation is given by , where is the Brillouin function.
To solve this problem, I transform it into a root-finding problem, specifically . I used MATLAB’s fzero and Mathematica’s FindRoot to solve this equation. However, I noticed that the results from the two methods are not consistent. The result from Mathematica matches the reference, while the MATLAB result also appears reasonable. In both cases, as a function of tends to zero from two different directions as increases.
Is this correct? Could you please comment or share your opinions on this matter?
Here is the MATLAB code:
clearvars; clc; close all; fclose all; format compact; format short;
B = @(J, x) ((2*J+1)/(2*J))*coth(((2*J+1)/(2*J))*x)-(1/(2*J)).*coth((1/(2*J))*x);
J = 1/2;
n = 101;
tau_array = linspace(0, 1.2, n);
m_array = zeros(1, n);
for i = 1:n
tau = tau_array(i);
fun = @(m) B(J, ((3*J)/(J+1))*m*(1/tau)) – m;
x = fzero(fun,[-1, 1]);
m_array(i) = x;
end
fig = figure();
ax = axes(fig);
plot(ax, tau_array, m_array,"LineWidth",2,"Color","red");
xlabel(‘Reudced temperature, tau’);
ylabel(‘Redueced magnetization, m’)
title(‘m as a function of tau’)
ax.TickDir = ‘out’;
Here is the Mathematica code:
Here is the reference result, which is taken from this paper [DOI: 10.1109/ISSE.2008.5276604; https://ieeexplore.ieee.org/document/5276604](See Equation 20 and Figure 3)
Thank you. Dear all, I am writing a small script to solve the temperature dependence of magnetization using a toy model. Mathematically, the problem is to determine the relation between reduced magnetization and reduced temperature . The equation is given by , where is the Brillouin function.
To solve this problem, I transform it into a root-finding problem, specifically . I used MATLAB’s fzero and Mathematica’s FindRoot to solve this equation. However, I noticed that the results from the two methods are not consistent. The result from Mathematica matches the reference, while the MATLAB result also appears reasonable. In both cases, as a function of tends to zero from two different directions as increases.
Is this correct? Could you please comment or share your opinions on this matter?
Here is the MATLAB code:
clearvars; clc; close all; fclose all; format compact; format short;
B = @(J, x) ((2*J+1)/(2*J))*coth(((2*J+1)/(2*J))*x)-(1/(2*J)).*coth((1/(2*J))*x);
J = 1/2;
n = 101;
tau_array = linspace(0, 1.2, n);
m_array = zeros(1, n);
for i = 1:n
tau = tau_array(i);
fun = @(m) B(J, ((3*J)/(J+1))*m*(1/tau)) – m;
x = fzero(fun,[-1, 1]);
m_array(i) = x;
end
fig = figure();
ax = axes(fig);
plot(ax, tau_array, m_array,"LineWidth",2,"Color","red");
xlabel(‘Reudced temperature, tau’);
ylabel(‘Redueced magnetization, m’)
title(‘m as a function of tau’)
ax.TickDir = ‘out’;
Here is the Mathematica code:
Here is the reference result, which is taken from this paper [DOI: 10.1109/ISSE.2008.5276604; https://ieeexplore.ieee.org/document/5276604](See Equation 20 and Figure 3)
Thank you. fzero, findroot MATLAB Answers — New Questions
Using iFFt to convert acceleration PSD ((m/s²)²/Hz) to random acceleration time series (m/s²)
Hello everybody,
I am trying to create a random acceleration time series from a given acceleration PSD ((m/s²)²/Hz). I have browsed some of the answers to similar questions in MATLAB community and put together few lines of code.. I do get a random acceleration time series but the acceleration amplitudes are really really small ( I would expect amplitudes at around max 130-140 m/s² and I get amplitudes around max 0.01-0.015 m/s² ). I have used randome phases for the time series. The time series is expected to have a sample rate of 2000Hz.
Please help me to understand where am I going wrong.
I have uploaded 2 MATLAB Files: psd_freq.mat contains the array of frequencies in the PSD (10-1000Hz), psd_values.mat contains the corresponding values of acceleration PSD with the units ((m/s²)²/Hz).
Thank you so much!
% This script generates a time series from a given PSD.
% Random phase angles are used to generate the time signal.
% The given PSD has freq from 10-1000Hz and the time series should also contain
% freq from 10-1000Hz.
% Desired time series duration is 12.8s.
%% Step 1
t_fin = 12.8; % duration of time signal (s)
Fr = 1/t_fin; % freq. resolution of PSD
%% Step 2
F0 = 10; % start freq. of time signal (Hz)
Fmax = 1000; % end freq. of time signal (Hz)
Fs = 2*Fmax; % sampling freq. of time signal
time = [0:1/Fs:t_fin]’; % time array
%% Step 3
% interpolating the given PSD
f = 0:Fr:Fmax;
PSD = [interp1(psd_freq, psd_disp_3150repeats, f)];
PSD(isnan(PSD))=0; % replace the non-existing frequencies in PSD with 0
%% Step 4
% calculating amplitudes from PSD
P1ampl = zeros(size(PSD));
for j=1:length(P1ampl)
if PSD(j)==0
P1ampl(j) = sqrt(Fr*PSD(j));
else
P1ampl(j) = sqrt(2*Fr*PSD(j));
end
end
P1ampl=P1ampl’;
%% Step 5
% generating random phases for the time series
P1phase = [rand(1, numel(P1ampl))*(2*pi)]’;
%% Step 6
P2 = [P1ampl.*exp(P1phase*1i)]’; % combining amplitudes and phases
P2=[P2,fliplr(conj(P2(2:end)))]; % flipping the array to make a fullsided array
%% Step 7
s=[ifft(P2)]’; % inverse FFT
plot(time,s)Hello everybody,
I am trying to create a random acceleration time series from a given acceleration PSD ((m/s²)²/Hz). I have browsed some of the answers to similar questions in MATLAB community and put together few lines of code.. I do get a random acceleration time series but the acceleration amplitudes are really really small ( I would expect amplitudes at around max 130-140 m/s² and I get amplitudes around max 0.01-0.015 m/s² ). I have used randome phases for the time series. The time series is expected to have a sample rate of 2000Hz.
Please help me to understand where am I going wrong.
I have uploaded 2 MATLAB Files: psd_freq.mat contains the array of frequencies in the PSD (10-1000Hz), psd_values.mat contains the corresponding values of acceleration PSD with the units ((m/s²)²/Hz).
Thank you so much!
% This script generates a time series from a given PSD.
% Random phase angles are used to generate the time signal.
% The given PSD has freq from 10-1000Hz and the time series should also contain
% freq from 10-1000Hz.
% Desired time series duration is 12.8s.
%% Step 1
t_fin = 12.8; % duration of time signal (s)
Fr = 1/t_fin; % freq. resolution of PSD
%% Step 2
F0 = 10; % start freq. of time signal (Hz)
Fmax = 1000; % end freq. of time signal (Hz)
Fs = 2*Fmax; % sampling freq. of time signal
time = [0:1/Fs:t_fin]’; % time array
%% Step 3
% interpolating the given PSD
f = 0:Fr:Fmax;
PSD = [interp1(psd_freq, psd_disp_3150repeats, f)];
PSD(isnan(PSD))=0; % replace the non-existing frequencies in PSD with 0
%% Step 4
% calculating amplitudes from PSD
P1ampl = zeros(size(PSD));
for j=1:length(P1ampl)
if PSD(j)==0
P1ampl(j) = sqrt(Fr*PSD(j));
else
P1ampl(j) = sqrt(2*Fr*PSD(j));
end
end
P1ampl=P1ampl’;
%% Step 5
% generating random phases for the time series
P1phase = [rand(1, numel(P1ampl))*(2*pi)]’;
%% Step 6
P2 = [P1ampl.*exp(P1phase*1i)]’; % combining amplitudes and phases
P2=[P2,fliplr(conj(P2(2:end)))]; % flipping the array to make a fullsided array
%% Step 7
s=[ifft(P2)]’; % inverse FFT
plot(time,s) Hello everybody,
I am trying to create a random acceleration time series from a given acceleration PSD ((m/s²)²/Hz). I have browsed some of the answers to similar questions in MATLAB community and put together few lines of code.. I do get a random acceleration time series but the acceleration amplitudes are really really small ( I would expect amplitudes at around max 130-140 m/s² and I get amplitudes around max 0.01-0.015 m/s² ). I have used randome phases for the time series. The time series is expected to have a sample rate of 2000Hz.
Please help me to understand where am I going wrong.
I have uploaded 2 MATLAB Files: psd_freq.mat contains the array of frequencies in the PSD (10-1000Hz), psd_values.mat contains the corresponding values of acceleration PSD with the units ((m/s²)²/Hz).
Thank you so much!
% This script generates a time series from a given PSD.
% Random phase angles are used to generate the time signal.
% The given PSD has freq from 10-1000Hz and the time series should also contain
% freq from 10-1000Hz.
% Desired time series duration is 12.8s.
%% Step 1
t_fin = 12.8; % duration of time signal (s)
Fr = 1/t_fin; % freq. resolution of PSD
%% Step 2
F0 = 10; % start freq. of time signal (Hz)
Fmax = 1000; % end freq. of time signal (Hz)
Fs = 2*Fmax; % sampling freq. of time signal
time = [0:1/Fs:t_fin]’; % time array
%% Step 3
% interpolating the given PSD
f = 0:Fr:Fmax;
PSD = [interp1(psd_freq, psd_disp_3150repeats, f)];
PSD(isnan(PSD))=0; % replace the non-existing frequencies in PSD with 0
%% Step 4
% calculating amplitudes from PSD
P1ampl = zeros(size(PSD));
for j=1:length(P1ampl)
if PSD(j)==0
P1ampl(j) = sqrt(Fr*PSD(j));
else
P1ampl(j) = sqrt(2*Fr*PSD(j));
end
end
P1ampl=P1ampl’;
%% Step 5
% generating random phases for the time series
P1phase = [rand(1, numel(P1ampl))*(2*pi)]’;
%% Step 6
P2 = [P1ampl.*exp(P1phase*1i)]’; % combining amplitudes and phases
P2=[P2,fliplr(conj(P2(2:end)))]; % flipping the array to make a fullsided array
%% Step 7
s=[ifft(P2)]’; % inverse FFT
plot(time,s) ifft, psd, time series, acceleration psd, psd to time series, fft MATLAB Answers — New Questions
gather() in tall array inverse is incorrect
Hi,
I am testing simple code with tall array inverse and gather(). The following results are different, anyone knows how to fix gather? As I am using tall array for AA and bb.
AA = ones(13,9);
bb = ones(13,1);
AA_t = tall(ones(13,9));
bb_t = tall(ones(13,1));
gather(AA_tbb_t);
AA bb;Hi,
I am testing simple code with tall array inverse and gather(). The following results are different, anyone knows how to fix gather? As I am using tall array for AA and bb.
AA = ones(13,9);
bb = ones(13,1);
AA_t = tall(ones(13,9));
bb_t = tall(ones(13,1));
gather(AA_tbb_t);
AA bb; Hi,
I am testing simple code with tall array inverse and gather(). The following results are different, anyone knows how to fix gather? As I am using tall array for AA and bb.
AA = ones(13,9);
bb = ones(13,1);
AA_t = tall(ones(13,9));
bb_t = tall(ones(13,1));
gather(AA_tbb_t);
AA bb; tall array, gather, inverse MATLAB Answers — New Questions
Laplacian sharpening filter in frequency domain
Hello everybody, I have written a code to do sharpening in frequency domain with Laplacian filter. The point is theLaplacian must be be between-1,1. Therefore it was divided to its max. I don’t know why it doesn’t work. I was wondering if anyone has any experience how to fix this problem? clear
close all
clc
a=imread(‘moon.tif’);
a=im2double(a);
subplot(2,3,1);
imshow(a);
title(‘Input image’);
[m,n]=size(a);
A=fft2(a);
subplot(2,3,2);
imshow(uint8(abs(A)));
title(‘F.T. of i/p without shift’);
A_shift=fftshift(A);
A_real=abs(A_shift);
subplot(2,3,3);
imshow(uint8(A_real));
title(‘F.T. of i/p after shift’);
A_high=zeros(m,n);
D=zeros(m,n);
for u=1:m
for v=1:n
H(u,v)=-4*(pi^2)*((u-(m./2))^2+(v-(n./2))^2);
end
end
% Get maximum value of Laplacian
max_val = max(abs(H),[],’all’);
% Normalize Laplacian to range [-1,1]
H_normalized = H / max_val;
% Compute inverse Fourier transform
Laplacian_inverse = ifft2((H_normalized.*A_shift));
% Get real part of Laplacian inverse
Laplacian_real = abs(Laplacian_inverse);
subplot(2,3,4);
imshow(H);
title(‘Laplacian filter’);
subplot(2,3,5);
mesh(H)
title(‘Surface plot BHPF’);
subplot(2,3,6);
imshow(uint8(Laplacian_real));
title(‘Laplacian HP filtered image’);Hello everybody, I have written a code to do sharpening in frequency domain with Laplacian filter. The point is theLaplacian must be be between-1,1. Therefore it was divided to its max. I don’t know why it doesn’t work. I was wondering if anyone has any experience how to fix this problem? clear
close all
clc
a=imread(‘moon.tif’);
a=im2double(a);
subplot(2,3,1);
imshow(a);
title(‘Input image’);
[m,n]=size(a);
A=fft2(a);
subplot(2,3,2);
imshow(uint8(abs(A)));
title(‘F.T. of i/p without shift’);
A_shift=fftshift(A);
A_real=abs(A_shift);
subplot(2,3,3);
imshow(uint8(A_real));
title(‘F.T. of i/p after shift’);
A_high=zeros(m,n);
D=zeros(m,n);
for u=1:m
for v=1:n
H(u,v)=-4*(pi^2)*((u-(m./2))^2+(v-(n./2))^2);
end
end
% Get maximum value of Laplacian
max_val = max(abs(H),[],’all’);
% Normalize Laplacian to range [-1,1]
H_normalized = H / max_val;
% Compute inverse Fourier transform
Laplacian_inverse = ifft2((H_normalized.*A_shift));
% Get real part of Laplacian inverse
Laplacian_real = abs(Laplacian_inverse);
subplot(2,3,4);
imshow(H);
title(‘Laplacian filter’);
subplot(2,3,5);
mesh(H)
title(‘Surface plot BHPF’);
subplot(2,3,6);
imshow(uint8(Laplacian_real));
title(‘Laplacian HP filtered image’); Hello everybody, I have written a code to do sharpening in frequency domain with Laplacian filter. The point is theLaplacian must be be between-1,1. Therefore it was divided to its max. I don’t know why it doesn’t work. I was wondering if anyone has any experience how to fix this problem? clear
close all
clc
a=imread(‘moon.tif’);
a=im2double(a);
subplot(2,3,1);
imshow(a);
title(‘Input image’);
[m,n]=size(a);
A=fft2(a);
subplot(2,3,2);
imshow(uint8(abs(A)));
title(‘F.T. of i/p without shift’);
A_shift=fftshift(A);
A_real=abs(A_shift);
subplot(2,3,3);
imshow(uint8(A_real));
title(‘F.T. of i/p after shift’);
A_high=zeros(m,n);
D=zeros(m,n);
for u=1:m
for v=1:n
H(u,v)=-4*(pi^2)*((u-(m./2))^2+(v-(n./2))^2);
end
end
% Get maximum value of Laplacian
max_val = max(abs(H),[],’all’);
% Normalize Laplacian to range [-1,1]
H_normalized = H / max_val;
% Compute inverse Fourier transform
Laplacian_inverse = ifft2((H_normalized.*A_shift));
% Get real part of Laplacian inverse
Laplacian_real = abs(Laplacian_inverse);
subplot(2,3,4);
imshow(H);
title(‘Laplacian filter’);
subplot(2,3,5);
mesh(H)
title(‘Surface plot BHPF’);
subplot(2,3,6);
imshow(uint8(Laplacian_real));
title(‘Laplacian HP filtered image’); frequency MATLAB Answers — New Questions
Simulink model: how to get cameraParams?
Hello,
so im building this simulink model in which I need the cameraParameters for computation. I tried the constant block to load the cameraParams in, but sadly the structure of the cameraParams is so convoluted, that It doesnt work.
Can Someone show me an easy way to get the cameraParams into the simulink model?
Thank you for any help!Hello,
so im building this simulink model in which I need the cameraParameters for computation. I tried the constant block to load the cameraParams in, but sadly the structure of the cameraParams is so convoluted, that It doesnt work.
Can Someone show me an easy way to get the cameraParams into the simulink model?
Thank you for any help! Hello,
so im building this simulink model in which I need the cameraParameters for computation. I tried the constant block to load the cameraParams in, but sadly the structure of the cameraParams is so convoluted, that It doesnt work.
Can Someone show me an easy way to get the cameraParams into the simulink model?
Thank you for any help! simulink, cameraparameters, image analysis, image processing MATLAB Answers — New Questions
error in using psat
Access to an object’s fields is only permitted within its methods.
Error in PVclass/setup_pv (line 54)
a.vbus = a.bus + Bus.n;
Error in fm_ncomp (line 37)
PV = setup_pv(PV);
Error in fm_spf (line 33)
fm_ncomp
Error in fm_set (line 720)
fm_spf
Error while evaluating UIControl Callback.
I got this error during load flow perform in matlab 2016a using psat 2.1.10Access to an object’s fields is only permitted within its methods.
Error in PVclass/setup_pv (line 54)
a.vbus = a.bus + Bus.n;
Error in fm_ncomp (line 37)
PV = setup_pv(PV);
Error in fm_spf (line 33)
fm_ncomp
Error in fm_set (line 720)
fm_spf
Error while evaluating UIControl Callback.
I got this error during load flow perform in matlab 2016a using psat 2.1.10 Access to an object’s fields is only permitted within its methods.
Error in PVclass/setup_pv (line 54)
a.vbus = a.bus + Bus.n;
Error in fm_ncomp (line 37)
PV = setup_pv(PV);
Error in fm_spf (line 33)
fm_ncomp
Error in fm_set (line 720)
fm_spf
Error while evaluating UIControl Callback.
I got this error during load flow perform in matlab 2016a using psat 2.1.10 psat matlab, simulink MATLAB Answers — New Questions
Unrecognized function or variable ‘fpval’.
Hello
Can you please guide me on how to fix the following error:
Unrecognized function or variable ‘fpval’.
Error in stepwisefit>stepcalc (line 368)
pval = fpval(fstat,df0,dfe);
Error in stepwisefit (line 150)
[B,SE,PVAL,stats] = stepcalc(allx,y,in);
Error in newrobuststepwise (line 28)
[b,se,pval1,inmodel1,stats,nextstep,history] = stepwisefit(Xdata,Ydata);
I used a stepwise function whose parameter pval is one of its outputsHello
Can you please guide me on how to fix the following error:
Unrecognized function or variable ‘fpval’.
Error in stepwisefit>stepcalc (line 368)
pval = fpval(fstat,df0,dfe);
Error in stepwisefit (line 150)
[B,SE,PVAL,stats] = stepcalc(allx,y,in);
Error in newrobuststepwise (line 28)
[b,se,pval1,inmodel1,stats,nextstep,history] = stepwisefit(Xdata,Ydata);
I used a stepwise function whose parameter pval is one of its outputs Hello
Can you please guide me on how to fix the following error:
Unrecognized function or variable ‘fpval’.
Error in stepwisefit>stepcalc (line 368)
pval = fpval(fstat,df0,dfe);
Error in stepwisefit (line 150)
[B,SE,PVAL,stats] = stepcalc(allx,y,in);
Error in newrobuststepwise (line 28)
[b,se,pval1,inmodel1,stats,nextstep,history] = stepwisefit(Xdata,Ydata);
I used a stepwise function whose parameter pval is one of its outputs stepwisefit, fpval MATLAB Answers — New Questions
Visualization of InterCellThermal connections in battery pack?
Hi,
I have created a 5S5P lithium ion battery pack with cylindrical cells using square topology. I have set the ambient thermal path to "cell based thermal resistance". In the module properties ,it says number of inter cell thermal connections are 20 and number of inter parallel assembly thermal connections are 52. My question is,
How these 20 and 52 thermal connections are happening? How can i visualize it? I don’t understand the matrix form of the above mentioned connections.
How the thermal resistance for each cell is calculated here? I want to model forced air convection. Is the pre set value of 1K/W goes well for my model?
How cell level ambient path thermal resistance is set as 25 K/W?How is it different from point number 2?
I have attached the image also for further reference.
Thank you.
SudeepHi,
I have created a 5S5P lithium ion battery pack with cylindrical cells using square topology. I have set the ambient thermal path to "cell based thermal resistance". In the module properties ,it says number of inter cell thermal connections are 20 and number of inter parallel assembly thermal connections are 52. My question is,
How these 20 and 52 thermal connections are happening? How can i visualize it? I don’t understand the matrix form of the above mentioned connections.
How the thermal resistance for each cell is calculated here? I want to model forced air convection. Is the pre set value of 1K/W goes well for my model?
How cell level ambient path thermal resistance is set as 25 K/W?How is it different from point number 2?
I have attached the image also for further reference.
Thank you.
Sudeep Hi,
I have created a 5S5P lithium ion battery pack with cylindrical cells using square topology. I have set the ambient thermal path to "cell based thermal resistance". In the module properties ,it says number of inter cell thermal connections are 20 and number of inter parallel assembly thermal connections are 52. My question is,
How these 20 and 52 thermal connections are happening? How can i visualize it? I don’t understand the matrix form of the above mentioned connections.
How the thermal resistance for each cell is calculated here? I want to model forced air convection. Is the pre set value of 1K/W goes well for my model?
How cell level ambient path thermal resistance is set as 25 K/W?How is it different from point number 2?
I have attached the image also for further reference.
Thank you.
Sudeep simscape battery, thermal resistance, heat transfer, thermal modeling MATLAB Answers — New Questions
Multiple language on custom tab
I have created my own Custom tab using Json files i have file Structure as
resources >> sl_toolstrip_plugins.json
>>json >> customTab.json
>> customTab_actions.json
>>arasTab_popups.json
from this structure i am loading my custom tab but when i change language of matlab all other tabs change language except custom tab.
how can i add Json of that language or how can i load my custom tab in that language. . . .?
how can i change language of my custom tab according to matlab language …?I have created my own Custom tab using Json files i have file Structure as
resources >> sl_toolstrip_plugins.json
>>json >> customTab.json
>> customTab_actions.json
>>arasTab_popups.json
from this structure i am loading my custom tab but when i change language of matlab all other tabs change language except custom tab.
how can i add Json of that language or how can i load my custom tab in that language. . . .?
how can i change language of my custom tab according to matlab language …? I have created my own Custom tab using Json files i have file Structure as
resources >> sl_toolstrip_plugins.json
>>json >> customTab.json
>> customTab_actions.json
>>arasTab_popups.json
from this structure i am loading my custom tab but when i change language of matlab all other tabs change language except custom tab.
how can i add Json of that language or how can i load my custom tab in that language. . . .?
how can i change language of my custom tab according to matlab language …? simulink, custom tab MATLAB Answers — New Questions
Why am I receiving an abnormal exit error when running “ar_0001” from the Model Advisor?
While executing check for ar_0001 on my models, I get an abnormal exit error
Abnormal exit: Unrecognized function or variable ‘non’.While executing check for ar_0001 on my models, I get an abnormal exit error
Abnormal exit: Unrecognized function or variable ‘non’. While executing check for ar_0001 on my models, I get an abnormal exit error
Abnormal exit: Unrecognized function or variable ‘non’. abnormal exit, mab MATLAB Answers — New Questions
Simulink Library Browser shows empty content of a custom library
He guys,
we have created a library with several sub-libraries and added them to the Simulink library browser using to the following tutorials:
https://de.mathworks.com/help/simulink/ug/creating-block-libraries.html
https://de.mathworks.com/help/simulink/ug/adding-libraries-to-the-library-browser.html
The library contains all sub-libraries as subsystem blocks,which opens the associated library using a callback function.
All, except one sub-library, are created correctly and you can see all blocks of each sub-library in the SL Browser. For reasons I don’t understand, the content of one sub-library is not displayed in the SL Browser. The content of this sublibrary is displayed blank. However, when I open this empty library from the SL Browser with right-click, it opens correctly and show me the correct content. This means, that this sublibrary was created correctly.
Does anyone have an idea how I can fix this error? I am at my wit’s end.
Thanks everybody and with best wishes,
LarsHe guys,
we have created a library with several sub-libraries and added them to the Simulink library browser using to the following tutorials:
https://de.mathworks.com/help/simulink/ug/creating-block-libraries.html
https://de.mathworks.com/help/simulink/ug/adding-libraries-to-the-library-browser.html
The library contains all sub-libraries as subsystem blocks,which opens the associated library using a callback function.
All, except one sub-library, are created correctly and you can see all blocks of each sub-library in the SL Browser. For reasons I don’t understand, the content of one sub-library is not displayed in the SL Browser. The content of this sublibrary is displayed blank. However, when I open this empty library from the SL Browser with right-click, it opens correctly and show me the correct content. This means, that this sublibrary was created correctly.
Does anyone have an idea how I can fix this error? I am at my wit’s end.
Thanks everybody and with best wishes,
Lars He guys,
we have created a library with several sub-libraries and added them to the Simulink library browser using to the following tutorials:
https://de.mathworks.com/help/simulink/ug/creating-block-libraries.html
https://de.mathworks.com/help/simulink/ug/adding-libraries-to-the-library-browser.html
The library contains all sub-libraries as subsystem blocks,which opens the associated library using a callback function.
All, except one sub-library, are created correctly and you can see all blocks of each sub-library in the SL Browser. For reasons I don’t understand, the content of one sub-library is not displayed in the SL Browser. The content of this sublibrary is displayed blank. However, when I open this empty library from the SL Browser with right-click, it opens correctly and show me the correct content. This means, that this sublibrary was created correctly.
Does anyone have an idea how I can fix this error? I am at my wit’s end.
Thanks everybody and with best wishes,
Lars simulink, custom library, blank library, sl browser MATLAB Answers — New Questions
Can’t stabilize system with PID
Hi. I’m trying to stabilize a model for this articol: https://ethz.ch/content/dam/ethz/special-interest/mavt/dynamic-systems-n-control/idsc-dam/Research_DAndrea/Cubli/Cubli_IROS2012.pdf , with a PID controller, and it’s not working. I don’t even know that this is the corect order of the cascade PID. I even try to take each individual part of the cascade PID and simulate it and use the tuner for that. And still it doesn’t working. Does anyone know what to do?
This is the cascade PID:
This is the attempt to try to take individual part of the cascade and simulate:
This is the Control System tuner:Hi. I’m trying to stabilize a model for this articol: https://ethz.ch/content/dam/ethz/special-interest/mavt/dynamic-systems-n-control/idsc-dam/Research_DAndrea/Cubli/Cubli_IROS2012.pdf , with a PID controller, and it’s not working. I don’t even know that this is the corect order of the cascade PID. I even try to take each individual part of the cascade PID and simulate it and use the tuner for that. And still it doesn’t working. Does anyone know what to do?
This is the cascade PID:
This is the attempt to try to take individual part of the cascade and simulate:
This is the Control System tuner: Hi. I’m trying to stabilize a model for this articol: https://ethz.ch/content/dam/ethz/special-interest/mavt/dynamic-systems-n-control/idsc-dam/Research_DAndrea/Cubli/Cubli_IROS2012.pdf , with a PID controller, and it’s not working. I don’t even know that this is the corect order of the cascade PID. I even try to take each individual part of the cascade PID and simulate it and use the tuner for that. And still it doesn’t working. Does anyone know what to do?
This is the cascade PID:
This is the attempt to try to take individual part of the cascade and simulate:
This is the Control System tuner: control, simulink, equation, model MATLAB Answers — New Questions