Tag Archives: matlab
Clave de activación de Matlab Simulink para estudiantes
Estimado,
¿Todo está bien?
Mi nombre es Roberta, soy estudiante de posgrado en la Universidad Federal de Bahía, en Brasil y me gustaría saber cómo puedo acceder a la clave de activación de Matlab Simulink para estudiantes.
¡Gracias de antemano!Estimado,
¿Todo está bien?
Mi nombre es Roberta, soy estudiante de posgrado en la Universidad Federal de Bahía, en Brasil y me gustaría saber cómo puedo acceder a la clave de activación de Matlab Simulink para estudiantes.
¡Gracias de antemano! Estimado,
¿Todo está bien?
Mi nombre es Roberta, soy estudiante de posgrado en la Universidad Federal de Bahía, en Brasil y me gustaría saber cómo puedo acceder a la clave de activación de Matlab Simulink para estudiantes.
¡Gracias de antemano! matlab code, clave de activación MATLAB Answers — New Questions
Using ss2tf when your matrices are variables without values yet
syms m b k
A = [0 (1/m+1/b);-k (-k/m-k/b)]
B = [0;k]
C = [0 1]
D = [0]
[b,a] = ss2tf(A,B,C,D)
I would like to get the transfer function of those matrices but the ss2tf function requires the matrices to be numerical. Is there a way to get a symbolic answer or am I looking at the wrong function?syms m b k
A = [0 (1/m+1/b);-k (-k/m-k/b)]
B = [0;k]
C = [0 1]
D = [0]
[b,a] = ss2tf(A,B,C,D)
I would like to get the transfer function of those matrices but the ss2tf function requires the matrices to be numerical. Is there a way to get a symbolic answer or am I looking at the wrong function? syms m b k
A = [0 (1/m+1/b);-k (-k/m-k/b)]
B = [0;k]
C = [0 1]
D = [0]
[b,a] = ss2tf(A,B,C,D)
I would like to get the transfer function of those matrices but the ss2tf function requires the matrices to be numerical. Is there a way to get a symbolic answer or am I looking at the wrong function? state space, transfer function MATLAB Answers — New Questions
Why did my MPC code not track the references?
I wrote code for the MPC controller to control a stable system to track to the desired value, but the system can not track the desired value, and I can not understand why the MPC controller can not track the desired value. Code I wrote as follows
t0 = 0 ;
tf = 40;
ts = 0.01;
t = t0:ts:tf ;
A = [0,0,0,0,0,1,0,0,0,0;0,0,0,0,0,0,1,0,0,0;0,0,0,0,0,0,0,1,0,0;0,0,0,0,0,0,0,0,1,0;0,0,0,0,0,0,0,0,0,1;-1967.63005780347,983.815028901734,0,0,0,-16.9768786127168,8.48843930635838,0,0,0;983.815028901734,-1967.63005780347,983.815028901734,0,0,8.48843930635838,-16.9768786127168,8.48843930635838,0,0;0,983.815028901734,-1967.63005780347,983.815028901734,0,0,8.48843930635838,-16.9768786127168,8.48843930635838,0;0,0,983.815028901734,-1967.63005780347,983.815028901734,0,0,8.48843930635838,-16.9768786127168,8.48843930635838;0,0,0,983.815028901734,-983.815028901734,0,0,0,8.48843930635838,-8.48843930635838];
B = [0,0,0,0,0;0,0,0,0,0;0,0,0,0,0;0,0,0,0,0;0,0,0,0,0;-0.00289017341040462,0,0,0,0;0,-0.00289017341040462,0,0,0;0,0,-0.00289017341040462,0,0;0,0,0,-0.00289017341040462,0;0,0,0,0,-0.00289017341040462];
C = [1,0,0,0,0,0,0,0,0,0;0,1,0,0,0,0,0,0,0,0;0,0,1,0,0,0,0,0,0,0;0,0,0,1,0,0,0,0,0,0;0,0,0,0,1,0,0,0,0,0;0,0,0,0,0,1,0,0,0,0;0,0,0,0,0,0,1,0,0,0;0,0,0,0,0,0,0,1,0,0;0,0,0,0,0,0,0,0,1,0;0,0,0,0,0,0,0,0,0,1]; ;
sys=ss(A,B,C,0);
sys1=c2d(sys,ts);
Am = sys1.a ;
Bm = sys1.b ;
Cm = sys1.c ;
n = size(Am ,1) ; % number of eigenvalues
q = size(Cm , 1) ; % number of outputs
m = size(Bm , 2) ; % number of inputs
Np =15 ; % Prediction Horizon
Nc = 10; % Control Horizon
F = zeros(q*Np , size(Am , 1)) ;
for i = 1:Np
F(q*i-q+1:q*i , 🙂 = Cm * Am^i ;
end
PHI = zeros(q * Np , m*Nc);
for i = 1:Np
for j = 1:i
PHI(q*i-q+1:q*i , m*j-m+1:m*j) = Cm * Am^(i-j) * Bm ;
end
end
PHI = PHI( : , 1:Nc*m) ;
%% Main Loop
Nt = numel(t) ;
%W = [ones(floor(Nt/4) , 1) ; 2*ones(floor(Nt/4) , 1) ; -ones(floor(Nt/4) , 1) ; zeros(floor(Nt/4+1) , 1)] ;
W = [ones(floor(Nt) , 1)]
y = zeros(q , Nt) ;
du = zeros(m , Nt) ;
u = zeros(m , Nt)
x = zeros(size(Am , 1) , Nt) ;
R = 1 ;
Fval = zeros(Nt , 1 ) ;
for i = 2:Nt-1
FreeResponse = F * x(: , i);
dU = (PHI’*PHI + R * size(PHI , 2))(PHI’ * (W(i) – FreeResponse)) ;
du(: , i) = dU(1:m) ;
x(: , i+1) = Am * x(: , i) + Bm * du(: ,i) ;
y(: , i+1) = Cm * x(: , i+1) ;
endI wrote code for the MPC controller to control a stable system to track to the desired value, but the system can not track the desired value, and I can not understand why the MPC controller can not track the desired value. Code I wrote as follows
t0 = 0 ;
tf = 40;
ts = 0.01;
t = t0:ts:tf ;
A = [0,0,0,0,0,1,0,0,0,0;0,0,0,0,0,0,1,0,0,0;0,0,0,0,0,0,0,1,0,0;0,0,0,0,0,0,0,0,1,0;0,0,0,0,0,0,0,0,0,1;-1967.63005780347,983.815028901734,0,0,0,-16.9768786127168,8.48843930635838,0,0,0;983.815028901734,-1967.63005780347,983.815028901734,0,0,8.48843930635838,-16.9768786127168,8.48843930635838,0,0;0,983.815028901734,-1967.63005780347,983.815028901734,0,0,8.48843930635838,-16.9768786127168,8.48843930635838,0;0,0,983.815028901734,-1967.63005780347,983.815028901734,0,0,8.48843930635838,-16.9768786127168,8.48843930635838;0,0,0,983.815028901734,-983.815028901734,0,0,0,8.48843930635838,-8.48843930635838];
B = [0,0,0,0,0;0,0,0,0,0;0,0,0,0,0;0,0,0,0,0;0,0,0,0,0;-0.00289017341040462,0,0,0,0;0,-0.00289017341040462,0,0,0;0,0,-0.00289017341040462,0,0;0,0,0,-0.00289017341040462,0;0,0,0,0,-0.00289017341040462];
C = [1,0,0,0,0,0,0,0,0,0;0,1,0,0,0,0,0,0,0,0;0,0,1,0,0,0,0,0,0,0;0,0,0,1,0,0,0,0,0,0;0,0,0,0,1,0,0,0,0,0;0,0,0,0,0,1,0,0,0,0;0,0,0,0,0,0,1,0,0,0;0,0,0,0,0,0,0,1,0,0;0,0,0,0,0,0,0,0,1,0;0,0,0,0,0,0,0,0,0,1]; ;
sys=ss(A,B,C,0);
sys1=c2d(sys,ts);
Am = sys1.a ;
Bm = sys1.b ;
Cm = sys1.c ;
n = size(Am ,1) ; % number of eigenvalues
q = size(Cm , 1) ; % number of outputs
m = size(Bm , 2) ; % number of inputs
Np =15 ; % Prediction Horizon
Nc = 10; % Control Horizon
F = zeros(q*Np , size(Am , 1)) ;
for i = 1:Np
F(q*i-q+1:q*i , 🙂 = Cm * Am^i ;
end
PHI = zeros(q * Np , m*Nc);
for i = 1:Np
for j = 1:i
PHI(q*i-q+1:q*i , m*j-m+1:m*j) = Cm * Am^(i-j) * Bm ;
end
end
PHI = PHI( : , 1:Nc*m) ;
%% Main Loop
Nt = numel(t) ;
%W = [ones(floor(Nt/4) , 1) ; 2*ones(floor(Nt/4) , 1) ; -ones(floor(Nt/4) , 1) ; zeros(floor(Nt/4+1) , 1)] ;
W = [ones(floor(Nt) , 1)]
y = zeros(q , Nt) ;
du = zeros(m , Nt) ;
u = zeros(m , Nt)
x = zeros(size(Am , 1) , Nt) ;
R = 1 ;
Fval = zeros(Nt , 1 ) ;
for i = 2:Nt-1
FreeResponse = F * x(: , i);
dU = (PHI’*PHI + R * size(PHI , 2))(PHI’ * (W(i) – FreeResponse)) ;
du(: , i) = dU(1:m) ;
x(: , i+1) = Am * x(: , i) + Bm * du(: ,i) ;
y(: , i+1) = Cm * x(: , i+1) ;
end I wrote code for the MPC controller to control a stable system to track to the desired value, but the system can not track the desired value, and I can not understand why the MPC controller can not track the desired value. Code I wrote as follows
t0 = 0 ;
tf = 40;
ts = 0.01;
t = t0:ts:tf ;
A = [0,0,0,0,0,1,0,0,0,0;0,0,0,0,0,0,1,0,0,0;0,0,0,0,0,0,0,1,0,0;0,0,0,0,0,0,0,0,1,0;0,0,0,0,0,0,0,0,0,1;-1967.63005780347,983.815028901734,0,0,0,-16.9768786127168,8.48843930635838,0,0,0;983.815028901734,-1967.63005780347,983.815028901734,0,0,8.48843930635838,-16.9768786127168,8.48843930635838,0,0;0,983.815028901734,-1967.63005780347,983.815028901734,0,0,8.48843930635838,-16.9768786127168,8.48843930635838,0;0,0,983.815028901734,-1967.63005780347,983.815028901734,0,0,8.48843930635838,-16.9768786127168,8.48843930635838;0,0,0,983.815028901734,-983.815028901734,0,0,0,8.48843930635838,-8.48843930635838];
B = [0,0,0,0,0;0,0,0,0,0;0,0,0,0,0;0,0,0,0,0;0,0,0,0,0;-0.00289017341040462,0,0,0,0;0,-0.00289017341040462,0,0,0;0,0,-0.00289017341040462,0,0;0,0,0,-0.00289017341040462,0;0,0,0,0,-0.00289017341040462];
C = [1,0,0,0,0,0,0,0,0,0;0,1,0,0,0,0,0,0,0,0;0,0,1,0,0,0,0,0,0,0;0,0,0,1,0,0,0,0,0,0;0,0,0,0,1,0,0,0,0,0;0,0,0,0,0,1,0,0,0,0;0,0,0,0,0,0,1,0,0,0;0,0,0,0,0,0,0,1,0,0;0,0,0,0,0,0,0,0,1,0;0,0,0,0,0,0,0,0,0,1]; ;
sys=ss(A,B,C,0);
sys1=c2d(sys,ts);
Am = sys1.a ;
Bm = sys1.b ;
Cm = sys1.c ;
n = size(Am ,1) ; % number of eigenvalues
q = size(Cm , 1) ; % number of outputs
m = size(Bm , 2) ; % number of inputs
Np =15 ; % Prediction Horizon
Nc = 10; % Control Horizon
F = zeros(q*Np , size(Am , 1)) ;
for i = 1:Np
F(q*i-q+1:q*i , 🙂 = Cm * Am^i ;
end
PHI = zeros(q * Np , m*Nc);
for i = 1:Np
for j = 1:i
PHI(q*i-q+1:q*i , m*j-m+1:m*j) = Cm * Am^(i-j) * Bm ;
end
end
PHI = PHI( : , 1:Nc*m) ;
%% Main Loop
Nt = numel(t) ;
%W = [ones(floor(Nt/4) , 1) ; 2*ones(floor(Nt/4) , 1) ; -ones(floor(Nt/4) , 1) ; zeros(floor(Nt/4+1) , 1)] ;
W = [ones(floor(Nt) , 1)]
y = zeros(q , Nt) ;
du = zeros(m , Nt) ;
u = zeros(m , Nt)
x = zeros(size(Am , 1) , Nt) ;
R = 1 ;
Fval = zeros(Nt , 1 ) ;
for i = 2:Nt-1
FreeResponse = F * x(: , i);
dU = (PHI’*PHI + R * size(PHI , 2))(PHI’ * (W(i) – FreeResponse)) ;
du(: , i) = dU(1:m) ;
x(: , i+1) = Am * x(: , i) + Bm * du(: ,i) ;
y(: , i+1) = Cm * x(: , i+1) ;
end mpc MATLAB Answers — New Questions
axtool tools are flickering and cannot be accessed
I am having a problem with the stability of the axtool menu bar. To investigate I created a simple app containing a single UIAxes and the default set of tools. When the mouse pointer is placed over the tool bar, the icons will flicker briefly and then disappear. Clicking the mouse causes the tools to appear briefly and then disappear again.and it seems next to impossible to select a single tool.I have used the axtool command sucessfully in recent times and I don’t understand what has changed.I am having a problem with the stability of the axtool menu bar. To investigate I created a simple app containing a single UIAxes and the default set of tools. When the mouse pointer is placed over the tool bar, the icons will flicker briefly and then disappear. Clicking the mouse causes the tools to appear briefly and then disappear again.and it seems next to impossible to select a single tool.I have used the axtool command sucessfully in recent times and I don’t understand what has changed. I am having a problem with the stability of the axtool menu bar. To investigate I created a simple app containing a single UIAxes and the default set of tools. When the mouse pointer is placed over the tool bar, the icons will flicker briefly and then disappear. Clicking the mouse causes the tools to appear briefly and then disappear again.and it seems next to impossible to select a single tool.I have used the axtool command sucessfully in recent times and I don’t understand what has changed. axtool MATLAB Answers — New Questions
Troubles with Experiment Manager Setup for LSTM regression
I need help!
I am managing Experiment Manager with a very simple exercise. I use data stocks for one-step ahead of the close price with a simple LSTM net. The net works well with trainnest(XTest,YTest,layers,options). I want to calibrate the Epochs parameters with Experiment Manager. I followed any suggestions and tutorials on the web but I can not do it. Xtest is an array with 6 cols (open, close, volum etc.) and 2401 (time steps) rows for a given stock. The reponse is a single 2401 vector containing one-time shifted of the close price. As said. I have no problem with trainnet and the net performs well.
I put data, layers and options in the script for Experiment Manager. Here is my code:
function [XTrain_N,YTrain_N,layers,options] = Experiment1_setup1(params)
load dati_net.mat XTrain_N YTrain_N
num_features = 6;
num_responses = 1;
num_hidden_units = 350;
layers = [
featureInputLayer(6);
lstmLayer(num_hidden_units, ‘OutputMode’,’last’)
fullyConnectedLayer(num_responses)
];
%Training Options
options = trainingOptions("adam", …
MaxEpochs=params.MaxEpochs, …
SequencePaddingDirection="left",…
InitialLearnRate=0.001,…
Shuffle="every-epoch", …
ValidationFrequency=50, …
GradientThreshold=.93, …
L2Regularization=0.00001, …
Verbose=false, …
Metrics="rmse", …
Plots="training-progress");
end
But when I run the experiment I always get:
The following errors occurred while running the experiment:
Errors occurred while validating the setup function: Caused by: Invalid output arguments from setup function. Third-from-last output of setup function must be a layer array or dlnetwork object, but a value of type ‘double’ was detected.
I tried dozens of trials but I am able to escape the problem. I attach also my data
Thanks in Advance!I need help!
I am managing Experiment Manager with a very simple exercise. I use data stocks for one-step ahead of the close price with a simple LSTM net. The net works well with trainnest(XTest,YTest,layers,options). I want to calibrate the Epochs parameters with Experiment Manager. I followed any suggestions and tutorials on the web but I can not do it. Xtest is an array with 6 cols (open, close, volum etc.) and 2401 (time steps) rows for a given stock. The reponse is a single 2401 vector containing one-time shifted of the close price. As said. I have no problem with trainnet and the net performs well.
I put data, layers and options in the script for Experiment Manager. Here is my code:
function [XTrain_N,YTrain_N,layers,options] = Experiment1_setup1(params)
load dati_net.mat XTrain_N YTrain_N
num_features = 6;
num_responses = 1;
num_hidden_units = 350;
layers = [
featureInputLayer(6);
lstmLayer(num_hidden_units, ‘OutputMode’,’last’)
fullyConnectedLayer(num_responses)
];
%Training Options
options = trainingOptions("adam", …
MaxEpochs=params.MaxEpochs, …
SequencePaddingDirection="left",…
InitialLearnRate=0.001,…
Shuffle="every-epoch", …
ValidationFrequency=50, …
GradientThreshold=.93, …
L2Regularization=0.00001, …
Verbose=false, …
Metrics="rmse", …
Plots="training-progress");
end
But when I run the experiment I always get:
The following errors occurred while running the experiment:
Errors occurred while validating the setup function: Caused by: Invalid output arguments from setup function. Third-from-last output of setup function must be a layer array or dlnetwork object, but a value of type ‘double’ was detected.
I tried dozens of trials but I am able to escape the problem. I attach also my data
Thanks in Advance! I need help!
I am managing Experiment Manager with a very simple exercise. I use data stocks for one-step ahead of the close price with a simple LSTM net. The net works well with trainnest(XTest,YTest,layers,options). I want to calibrate the Epochs parameters with Experiment Manager. I followed any suggestions and tutorials on the web but I can not do it. Xtest is an array with 6 cols (open, close, volum etc.) and 2401 (time steps) rows for a given stock. The reponse is a single 2401 vector containing one-time shifted of the close price. As said. I have no problem with trainnet and the net performs well.
I put data, layers and options in the script for Experiment Manager. Here is my code:
function [XTrain_N,YTrain_N,layers,options] = Experiment1_setup1(params)
load dati_net.mat XTrain_N YTrain_N
num_features = 6;
num_responses = 1;
num_hidden_units = 350;
layers = [
featureInputLayer(6);
lstmLayer(num_hidden_units, ‘OutputMode’,’last’)
fullyConnectedLayer(num_responses)
];
%Training Options
options = trainingOptions("adam", …
MaxEpochs=params.MaxEpochs, …
SequencePaddingDirection="left",…
InitialLearnRate=0.001,…
Shuffle="every-epoch", …
ValidationFrequency=50, …
GradientThreshold=.93, …
L2Regularization=0.00001, …
Verbose=false, …
Metrics="rmse", …
Plots="training-progress");
end
But when I run the experiment I always get:
The following errors occurred while running the experiment:
Errors occurred while validating the setup function: Caused by: Invalid output arguments from setup function. Third-from-last output of setup function must be a layer array or dlnetwork object, but a value of type ‘double’ was detected.
I tried dozens of trials but I am able to escape the problem. I attach also my data
Thanks in Advance! experiment manager MATLAB Answers — New Questions
RL: Continuous action space, but within a desired range(use PPO)
I am now trying to use a PPO in RL training with continuous action space.
However, I want to ensure that the output of my actor always stays within the upper and lower bounds I set. In my environment, I’m using the following code, and my actor network and critic network are as follows.
% observation info
ObservationInfo = rlNumericSpec([n_Pd+n_Pg+1, 1]);
% action info
ActionInfo = rlNumericSpec([n_Pg, 1], …
‘Lowerlimit’, Pgmin, …
‘Upperlimit’, Pgmax);
Actor network
%% Actor Network
% Input path layers
inPath = [featureInputLayer(numObservations,’Normalization’,’none’,’Name’,’observation’)
fullyConnectedLayer(128,’Name’,’ActorFC1′)
reluLayer(‘Name’,’ActorRelu1′)
fullyConnectedLayer(128,’Name’,’ActorFC2′)
reluLayer(‘Name’, ‘ActorRelu2’)
fullyConnectedLayer(numActions,’Name’,’Action’)
];
% Path layers for mean value
meanPath = [
tanhLayer(Name="tanhMean");
fullyConnectedLayer(numActions);
scalingLayer(‘Name’,’ActorScaling’,’Scale’,actInfo.UpperLimit)
];
% Path layers for standard deviations
% Using softplus layer to make them non negative
sdevPath = [
tanhLayer(Name="tanhStdv");
fullyConnectedLayer(numActions);
softplusLayer(Name="Splus")
];
% Add layers to network object
actorNetwork = layerGraph(inPath);
actorNetwork = addLayers(actorNetwork,meanPath);
actorNetwork = addLayers(actorNetwork,sdevPath);
% Connect layers
actorNetwork = connectLayers(actorNetwork,"Action","tanhMean/in");
actorNetwork = connectLayers(actorNetwork,"Action","tanhStdv/in");
actorNetwork = dlnetwork(actorNetwork);
% figure(2)
% plot(layerGraph(actorNetwork))
% Setting Actor
actorOptions = rlOptimizerOptions(‘LearnRate’,0.1,’GradientThreshold’,inf);
actor = rlContinuousGaussianActor(actorNetwork,obsInfo,actInfo, …
"ActionMeanOutputNames","ActorScaling", …
"ActionStandardDeviationOutputNames","Splus");
Critic network
%% Critic Network
criticNetwork = [
featureInputLayer(numObservations,’Normalization’,’none’,’Name’,’observation’)
fullyConnectedLayer(128,’Name’,’CriticFC1′)
reluLayer(‘Name’,’CriticRelu1′)
fullyConnectedLayer(1,’Name’,’CriticOutput’)];
criticNetwork = dlnetwork(criticNetwork);
% Setting Critic
criticOptions = rlOptimizerOptions(‘LearnRate’,0.1,’GradientThreshold’,inf);
critic = rlValueFunction(criticNetwork,obsInfo);
something eles
%% Create PPO Agent
% Setting PPO Agent Options
agentOptions = rlPPOAgentOptions(…
‘SampleTime’,Ts,…
‘ActorOptimizerOptions’,actorOptions,…
‘CriticOptimizerOptions’,criticOptions,…
‘ExperienceHorizon’,600,…
‘ClipFactor’,0.02,…
‘EntropyLossWeight’,0.01,…
‘MiniBatchSize’,300, …
‘AdvantageEstimateMethod’,’gae’,…
‘GAEFactor’,0.95,…
‘DiscountFactor’,0.99);
% Create Agent
agent = rlPPOAgent(actor,critic,agentOptions);
%% Train Agent
maxepisodes = 10000;
maxsteps = ceil(Nt/Ts);
trainingOptions = rlTrainingOptions(…
‘MaxEpisodes’,maxepisodes,…
‘MaxStepsPerEpisode’,maxsteps,…
‘StopOnError’,"on",…
‘Plots’,"training-progress",…
‘StopTrainingCriteria’,"AverageReward",…
‘StopTrainingValue’,-14500,…
‘SaveAgentCriteria’,"EpisodeReward",…
‘SaveAgentValue’,-14500);
% train? 1-train; 0-not train
doTraining = 1;
if doTraining
% Train the agent.
trainingStats = train(agent,env,trainingOptions);
save(‘XXX.mat’,’agent’)
else
% Load the pretrained agent for the example.
load(‘XXX.mat’,’agent’)
end
THANKS!I am now trying to use a PPO in RL training with continuous action space.
However, I want to ensure that the output of my actor always stays within the upper and lower bounds I set. In my environment, I’m using the following code, and my actor network and critic network are as follows.
% observation info
ObservationInfo = rlNumericSpec([n_Pd+n_Pg+1, 1]);
% action info
ActionInfo = rlNumericSpec([n_Pg, 1], …
‘Lowerlimit’, Pgmin, …
‘Upperlimit’, Pgmax);
Actor network
%% Actor Network
% Input path layers
inPath = [featureInputLayer(numObservations,’Normalization’,’none’,’Name’,’observation’)
fullyConnectedLayer(128,’Name’,’ActorFC1′)
reluLayer(‘Name’,’ActorRelu1′)
fullyConnectedLayer(128,’Name’,’ActorFC2′)
reluLayer(‘Name’, ‘ActorRelu2’)
fullyConnectedLayer(numActions,’Name’,’Action’)
];
% Path layers for mean value
meanPath = [
tanhLayer(Name="tanhMean");
fullyConnectedLayer(numActions);
scalingLayer(‘Name’,’ActorScaling’,’Scale’,actInfo.UpperLimit)
];
% Path layers for standard deviations
% Using softplus layer to make them non negative
sdevPath = [
tanhLayer(Name="tanhStdv");
fullyConnectedLayer(numActions);
softplusLayer(Name="Splus")
];
% Add layers to network object
actorNetwork = layerGraph(inPath);
actorNetwork = addLayers(actorNetwork,meanPath);
actorNetwork = addLayers(actorNetwork,sdevPath);
% Connect layers
actorNetwork = connectLayers(actorNetwork,"Action","tanhMean/in");
actorNetwork = connectLayers(actorNetwork,"Action","tanhStdv/in");
actorNetwork = dlnetwork(actorNetwork);
% figure(2)
% plot(layerGraph(actorNetwork))
% Setting Actor
actorOptions = rlOptimizerOptions(‘LearnRate’,0.1,’GradientThreshold’,inf);
actor = rlContinuousGaussianActor(actorNetwork,obsInfo,actInfo, …
"ActionMeanOutputNames","ActorScaling", …
"ActionStandardDeviationOutputNames","Splus");
Critic network
%% Critic Network
criticNetwork = [
featureInputLayer(numObservations,’Normalization’,’none’,’Name’,’observation’)
fullyConnectedLayer(128,’Name’,’CriticFC1′)
reluLayer(‘Name’,’CriticRelu1′)
fullyConnectedLayer(1,’Name’,’CriticOutput’)];
criticNetwork = dlnetwork(criticNetwork);
% Setting Critic
criticOptions = rlOptimizerOptions(‘LearnRate’,0.1,’GradientThreshold’,inf);
critic = rlValueFunction(criticNetwork,obsInfo);
something eles
%% Create PPO Agent
% Setting PPO Agent Options
agentOptions = rlPPOAgentOptions(…
‘SampleTime’,Ts,…
‘ActorOptimizerOptions’,actorOptions,…
‘CriticOptimizerOptions’,criticOptions,…
‘ExperienceHorizon’,600,…
‘ClipFactor’,0.02,…
‘EntropyLossWeight’,0.01,…
‘MiniBatchSize’,300, …
‘AdvantageEstimateMethod’,’gae’,…
‘GAEFactor’,0.95,…
‘DiscountFactor’,0.99);
% Create Agent
agent = rlPPOAgent(actor,critic,agentOptions);
%% Train Agent
maxepisodes = 10000;
maxsteps = ceil(Nt/Ts);
trainingOptions = rlTrainingOptions(…
‘MaxEpisodes’,maxepisodes,…
‘MaxStepsPerEpisode’,maxsteps,…
‘StopOnError’,"on",…
‘Plots’,"training-progress",…
‘StopTrainingCriteria’,"AverageReward",…
‘StopTrainingValue’,-14500,…
‘SaveAgentCriteria’,"EpisodeReward",…
‘SaveAgentValue’,-14500);
% train? 1-train; 0-not train
doTraining = 1;
if doTraining
% Train the agent.
trainingStats = train(agent,env,trainingOptions);
save(‘XXX.mat’,’agent’)
else
% Load the pretrained agent for the example.
load(‘XXX.mat’,’agent’)
end
THANKS! I am now trying to use a PPO in RL training with continuous action space.
However, I want to ensure that the output of my actor always stays within the upper and lower bounds I set. In my environment, I’m using the following code, and my actor network and critic network are as follows.
% observation info
ObservationInfo = rlNumericSpec([n_Pd+n_Pg+1, 1]);
% action info
ActionInfo = rlNumericSpec([n_Pg, 1], …
‘Lowerlimit’, Pgmin, …
‘Upperlimit’, Pgmax);
Actor network
%% Actor Network
% Input path layers
inPath = [featureInputLayer(numObservations,’Normalization’,’none’,’Name’,’observation’)
fullyConnectedLayer(128,’Name’,’ActorFC1′)
reluLayer(‘Name’,’ActorRelu1′)
fullyConnectedLayer(128,’Name’,’ActorFC2′)
reluLayer(‘Name’, ‘ActorRelu2’)
fullyConnectedLayer(numActions,’Name’,’Action’)
];
% Path layers for mean value
meanPath = [
tanhLayer(Name="tanhMean");
fullyConnectedLayer(numActions);
scalingLayer(‘Name’,’ActorScaling’,’Scale’,actInfo.UpperLimit)
];
% Path layers for standard deviations
% Using softplus layer to make them non negative
sdevPath = [
tanhLayer(Name="tanhStdv");
fullyConnectedLayer(numActions);
softplusLayer(Name="Splus")
];
% Add layers to network object
actorNetwork = layerGraph(inPath);
actorNetwork = addLayers(actorNetwork,meanPath);
actorNetwork = addLayers(actorNetwork,sdevPath);
% Connect layers
actorNetwork = connectLayers(actorNetwork,"Action","tanhMean/in");
actorNetwork = connectLayers(actorNetwork,"Action","tanhStdv/in");
actorNetwork = dlnetwork(actorNetwork);
% figure(2)
% plot(layerGraph(actorNetwork))
% Setting Actor
actorOptions = rlOptimizerOptions(‘LearnRate’,0.1,’GradientThreshold’,inf);
actor = rlContinuousGaussianActor(actorNetwork,obsInfo,actInfo, …
"ActionMeanOutputNames","ActorScaling", …
"ActionStandardDeviationOutputNames","Splus");
Critic network
%% Critic Network
criticNetwork = [
featureInputLayer(numObservations,’Normalization’,’none’,’Name’,’observation’)
fullyConnectedLayer(128,’Name’,’CriticFC1′)
reluLayer(‘Name’,’CriticRelu1′)
fullyConnectedLayer(1,’Name’,’CriticOutput’)];
criticNetwork = dlnetwork(criticNetwork);
% Setting Critic
criticOptions = rlOptimizerOptions(‘LearnRate’,0.1,’GradientThreshold’,inf);
critic = rlValueFunction(criticNetwork,obsInfo);
something eles
%% Create PPO Agent
% Setting PPO Agent Options
agentOptions = rlPPOAgentOptions(…
‘SampleTime’,Ts,…
‘ActorOptimizerOptions’,actorOptions,…
‘CriticOptimizerOptions’,criticOptions,…
‘ExperienceHorizon’,600,…
‘ClipFactor’,0.02,…
‘EntropyLossWeight’,0.01,…
‘MiniBatchSize’,300, …
‘AdvantageEstimateMethod’,’gae’,…
‘GAEFactor’,0.95,…
‘DiscountFactor’,0.99);
% Create Agent
agent = rlPPOAgent(actor,critic,agentOptions);
%% Train Agent
maxepisodes = 10000;
maxsteps = ceil(Nt/Ts);
trainingOptions = rlTrainingOptions(…
‘MaxEpisodes’,maxepisodes,…
‘MaxStepsPerEpisode’,maxsteps,…
‘StopOnError’,"on",…
‘Plots’,"training-progress",…
‘StopTrainingCriteria’,"AverageReward",…
‘StopTrainingValue’,-14500,…
‘SaveAgentCriteria’,"EpisodeReward",…
‘SaveAgentValue’,-14500);
% train? 1-train; 0-not train
doTraining = 1;
if doTraining
% Train the agent.
trainingStats = train(agent,env,trainingOptions);
save(‘XXX.mat’,’agent’)
else
% Load the pretrained agent for the example.
load(‘XXX.mat’,’agent’)
end
THANKS! reinforcement learning, agent MATLAB Answers — New Questions
Parse error at observed data
% Define the SITR model as a system of ODEs
function dydt = SITRModel(t, y, beta, gamma, delta, alpha, lambda, mu, N)
S = y(1); % Susceptible
I = y(2); % Infectious
Q = y(3); % Isolated
T = y(4); % Treated
R = y(5); % Recovered
dSdt = -beta * S * I / N;
dIdt = beta * S * I / N – gamma * I – delta * I – alpha * I;
dQdt = delta * I – lambda * Q;
dTdt = alpha * I – mu * T;
dRdt = gamma * I + lambda * Q + mu * T;
dydt = [dSdt; dIdt; dQdt; dTdt; dRdt];
end
% Observed data (replace with actual data)
% Format: [time, infected, isolated, treated, recovered]
observed_data = [
0, 1, 0, 0, 0;
10, 50, 10, 5, 15;
20, 100, 25, 15, 50;
30, 150, 35, 30, 100;
40, 200, 50, 50, 200
];
% Initial conditions
N = 1000000; % Total population
S0 = N – 1;
I0 = 1;
Q0 = 0;
T0 = 0;
R0 = 0;
y0 = [S0, I0, Q0, T0, R0];
% Time points for the solution (based on observed data)
tspan = observed_data(:, 1);
% Define the objective function for optimization
function error = objectiveFunction(params)
beta = params(1);
gamma = params(2);
delta = params(3);
alpha = params(4);
lambda = params(5);
mu = params(6);
% Solve the ODE with the current parameters
[t, y] = ode45(@(t, y) SITRModel(t, y, beta, gamma, delta, alpha, lambda, mu, N), tspan, y0);
% Interpolate the model’s output to match the time points of observed data
model_values = interp1(t, y(:, 2:5), tspan);
% Calculate the sum of squared errors
error = sum((model_values – observed_data(:, 2:5)).^2, ‘all’);
end
% Initial guess for parameters [beta, gamma, delta, alpha, lambda, mu]
initial_params = [0.3, 0.1, 0.05, 0.02, 0.1, 0.1];
% Perform optimization using fminsearch
options = optimset(‘MaxFunEvals’, 1000, ‘MaxIter’, 1000);
optimized_params = fminsearch(@objectiveFunction, initial_params, options);
% Display optimized parameters
disp(‘Optimized parameters:’);
disp(optimized_params);
% Solve the system with optimized parameters
[t, y] = ode45(@(t, y) SITRModel(t, y, optimized_params(1), optimized_params(2), optimized_params(3), optimized_params(4), optimized_params(5), optimized_params(6), N), linspace(0, 160, 100), y0);
% Plot the solution with optimized parameters
figure;
plot(t, y(:, 1), ‘b-‘, t, y(:, 2), ‘r-‘, t, y(:, 3), ‘g-‘, t, y(:, 4), ‘m-‘, t, y(:, 5), ‘k-‘);
legend(‘Susceptible’, ‘Infectious’, ‘Isolated’, ‘Treated’, ‘Recovered’);
title(‘Fitted SITR Model for COVID-19’);
xlabel(‘Days’);
ylabel(‘Population’);
grid on;% Define the SITR model as a system of ODEs
function dydt = SITRModel(t, y, beta, gamma, delta, alpha, lambda, mu, N)
S = y(1); % Susceptible
I = y(2); % Infectious
Q = y(3); % Isolated
T = y(4); % Treated
R = y(5); % Recovered
dSdt = -beta * S * I / N;
dIdt = beta * S * I / N – gamma * I – delta * I – alpha * I;
dQdt = delta * I – lambda * Q;
dTdt = alpha * I – mu * T;
dRdt = gamma * I + lambda * Q + mu * T;
dydt = [dSdt; dIdt; dQdt; dTdt; dRdt];
end
% Observed data (replace with actual data)
% Format: [time, infected, isolated, treated, recovered]
observed_data = [
0, 1, 0, 0, 0;
10, 50, 10, 5, 15;
20, 100, 25, 15, 50;
30, 150, 35, 30, 100;
40, 200, 50, 50, 200
];
% Initial conditions
N = 1000000; % Total population
S0 = N – 1;
I0 = 1;
Q0 = 0;
T0 = 0;
R0 = 0;
y0 = [S0, I0, Q0, T0, R0];
% Time points for the solution (based on observed data)
tspan = observed_data(:, 1);
% Define the objective function for optimization
function error = objectiveFunction(params)
beta = params(1);
gamma = params(2);
delta = params(3);
alpha = params(4);
lambda = params(5);
mu = params(6);
% Solve the ODE with the current parameters
[t, y] = ode45(@(t, y) SITRModel(t, y, beta, gamma, delta, alpha, lambda, mu, N), tspan, y0);
% Interpolate the model’s output to match the time points of observed data
model_values = interp1(t, y(:, 2:5), tspan);
% Calculate the sum of squared errors
error = sum((model_values – observed_data(:, 2:5)).^2, ‘all’);
end
% Initial guess for parameters [beta, gamma, delta, alpha, lambda, mu]
initial_params = [0.3, 0.1, 0.05, 0.02, 0.1, 0.1];
% Perform optimization using fminsearch
options = optimset(‘MaxFunEvals’, 1000, ‘MaxIter’, 1000);
optimized_params = fminsearch(@objectiveFunction, initial_params, options);
% Display optimized parameters
disp(‘Optimized parameters:’);
disp(optimized_params);
% Solve the system with optimized parameters
[t, y] = ode45(@(t, y) SITRModel(t, y, optimized_params(1), optimized_params(2), optimized_params(3), optimized_params(4), optimized_params(5), optimized_params(6), N), linspace(0, 160, 100), y0);
% Plot the solution with optimized parameters
figure;
plot(t, y(:, 1), ‘b-‘, t, y(:, 2), ‘r-‘, t, y(:, 3), ‘g-‘, t, y(:, 4), ‘m-‘, t, y(:, 5), ‘k-‘);
legend(‘Susceptible’, ‘Infectious’, ‘Isolated’, ‘Treated’, ‘Recovered’);
title(‘Fitted SITR Model for COVID-19’);
xlabel(‘Days’);
ylabel(‘Population’);
grid on; % Define the SITR model as a system of ODEs
function dydt = SITRModel(t, y, beta, gamma, delta, alpha, lambda, mu, N)
S = y(1); % Susceptible
I = y(2); % Infectious
Q = y(3); % Isolated
T = y(4); % Treated
R = y(5); % Recovered
dSdt = -beta * S * I / N;
dIdt = beta * S * I / N – gamma * I – delta * I – alpha * I;
dQdt = delta * I – lambda * Q;
dTdt = alpha * I – mu * T;
dRdt = gamma * I + lambda * Q + mu * T;
dydt = [dSdt; dIdt; dQdt; dTdt; dRdt];
end
% Observed data (replace with actual data)
% Format: [time, infected, isolated, treated, recovered]
observed_data = [
0, 1, 0, 0, 0;
10, 50, 10, 5, 15;
20, 100, 25, 15, 50;
30, 150, 35, 30, 100;
40, 200, 50, 50, 200
];
% Initial conditions
N = 1000000; % Total population
S0 = N – 1;
I0 = 1;
Q0 = 0;
T0 = 0;
R0 = 0;
y0 = [S0, I0, Q0, T0, R0];
% Time points for the solution (based on observed data)
tspan = observed_data(:, 1);
% Define the objective function for optimization
function error = objectiveFunction(params)
beta = params(1);
gamma = params(2);
delta = params(3);
alpha = params(4);
lambda = params(5);
mu = params(6);
% Solve the ODE with the current parameters
[t, y] = ode45(@(t, y) SITRModel(t, y, beta, gamma, delta, alpha, lambda, mu, N), tspan, y0);
% Interpolate the model’s output to match the time points of observed data
model_values = interp1(t, y(:, 2:5), tspan);
% Calculate the sum of squared errors
error = sum((model_values – observed_data(:, 2:5)).^2, ‘all’);
end
% Initial guess for parameters [beta, gamma, delta, alpha, lambda, mu]
initial_params = [0.3, 0.1, 0.05, 0.02, 0.1, 0.1];
% Perform optimization using fminsearch
options = optimset(‘MaxFunEvals’, 1000, ‘MaxIter’, 1000);
optimized_params = fminsearch(@objectiveFunction, initial_params, options);
% Display optimized parameters
disp(‘Optimized parameters:’);
disp(optimized_params);
% Solve the system with optimized parameters
[t, y] = ode45(@(t, y) SITRModel(t, y, optimized_params(1), optimized_params(2), optimized_params(3), optimized_params(4), optimized_params(5), optimized_params(6), N), linspace(0, 160, 100), y0);
% Plot the solution with optimized parameters
figure;
plot(t, y(:, 1), ‘b-‘, t, y(:, 2), ‘r-‘, t, y(:, 3), ‘g-‘, t, y(:, 4), ‘m-‘, t, y(:, 5), ‘k-‘);
legend(‘Susceptible’, ‘Infectious’, ‘Isolated’, ‘Treated’, ‘Recovered’);
title(‘Fitted SITR Model for COVID-19’);
xlabel(‘Days’);
ylabel(‘Population’);
grid on; parse error MATLAB Answers — New Questions
How can I find the set of vertices of hexagons which are adjacent to a random point?
I have a set of hexagons whose blue coordinates are known:
I have a random red point and I need to know the 4 (in some cases it would be 3) points which are immediately adjacent to it. These points are contained in the black box shown for illustration.
I tried to sort the blue points by measuring distances but I keep getting extra points (shown by black arrows) or missing the required points.I have a set of hexagons whose blue coordinates are known:
I have a random red point and I need to know the 4 (in some cases it would be 3) points which are immediately adjacent to it. These points are contained in the black box shown for illustration.
I tried to sort the blue points by measuring distances but I keep getting extra points (shown by black arrows) or missing the required points. I have a set of hexagons whose blue coordinates are known:
I have a random red point and I need to know the 4 (in some cases it would be 3) points which are immediately adjacent to it. These points are contained in the black box shown for illustration.
I tried to sort the blue points by measuring distances but I keep getting extra points (shown by black arrows) or missing the required points. mathematics, data MATLAB Answers — New Questions
How can I compress text file by Huffman encoding method by using matlab
To compress the text fileTo compress the text file To compress the text file huffman encoding MATLAB Answers — New Questions
Stop Data Acquisition when Needed
Hello,
I am building a data aquisition program using NI devices. I developed a program using the data aquisition toolbox, however the code that I have needs a run time as input which is only when I know the data aquisition time.
However in cases when I need to stop the data aquisition before the set input time, I am unable to do so before the complete run is done.
Is there a way to stop the program and still have access to the aquired data because if I stop the program, the workspace clears out and there in no data there or is there a way I can continously add data into a buffer which the data is being read so that even if the program is stipped, the aquired data is accessible.
I have attached my code for review.
close all
clear all
clc
%% Create a data acquisition session
daqSession = daq.createSession(‘ni’);
%% Add channels specified by subsystem type and device
daqSession.addAnalogInputChannel(‘Dev1′,’ai0′,’Bridge’);
daqSession.addAnalogInputChannel(‘Dev1′,’ai1′,’Bridge’);
daqSession.addAnalogInputChannel(‘Dev1′,’ai2′,’Bridge’);
daqSession.addAnalogInputChannel(‘Dev1′,’ai3′,’Bridge’);
%% Configure properties
daqSession.Rate = 1653;
daqSession.IsContinuous = 1;
hlistener = daqSession.addlistener(‘DataAvailable’,@(src,event) plot(event.TimeStamps, event.Data));
daqSession.IsContinuous = 0;
daqSession.DurationInSeconds = 1800;
daqSession.Channels(1).BridgeMode = ‘Full’;
daqSession.Channels(1).ExcitationVoltage = 5;
daqSession.Channels(1).NominalBridgeResistance = 1;
daqSession.Channels(1).Name = ‘Kulite 1’;
daqSession.Channels(2).BridgeMode = ‘Full’;
daqSession.Channels(2).NominalBridgeResistance = 1;
daqSession.Channels(2).Name = ‘Kulite2’;
daqSession.Channels(3).BridgeMode = ‘Full’;
daqSession.Channels(3).NominalBridgeResistance = 1;
daqSession.Channels(3).Name = ‘Kulite3’;
daqSession.Channels(4).BridgeMode = ‘Full’;
daqSession.Channels(4).NominalBridgeResistance = 1;
daqSession.Channels(4).Name = ‘Kulite4’;
%Read supplied voltage
V=daqSession.Channels(1).ExcitationVoltage;
%% Run the data acquisition session
[data,time] = daqSession.startForeground();
figure
plot(time,data)
%Take values from DAQ Matrix
V1=data(:,1);
V2=data(:,2);
V3=data(:,3);
V4=data(:,4);
%Create Matrix for other Time and Pressure Values
Voltagedata=[time,V1,V2,V3,V4];
fileName = sprintf(‘RawVData_%s.csv’, datestr(now, ‘yyyymmdd_HHMMSS’))
writematrix(Voltagedata,fileName)
%% Disconnect from the device
daqSession.release();
delete(daqSession);
clear daqSession;Hello,
I am building a data aquisition program using NI devices. I developed a program using the data aquisition toolbox, however the code that I have needs a run time as input which is only when I know the data aquisition time.
However in cases when I need to stop the data aquisition before the set input time, I am unable to do so before the complete run is done.
Is there a way to stop the program and still have access to the aquired data because if I stop the program, the workspace clears out and there in no data there or is there a way I can continously add data into a buffer which the data is being read so that even if the program is stipped, the aquired data is accessible.
I have attached my code for review.
close all
clear all
clc
%% Create a data acquisition session
daqSession = daq.createSession(‘ni’);
%% Add channels specified by subsystem type and device
daqSession.addAnalogInputChannel(‘Dev1′,’ai0′,’Bridge’);
daqSession.addAnalogInputChannel(‘Dev1′,’ai1′,’Bridge’);
daqSession.addAnalogInputChannel(‘Dev1′,’ai2′,’Bridge’);
daqSession.addAnalogInputChannel(‘Dev1′,’ai3′,’Bridge’);
%% Configure properties
daqSession.Rate = 1653;
daqSession.IsContinuous = 1;
hlistener = daqSession.addlistener(‘DataAvailable’,@(src,event) plot(event.TimeStamps, event.Data));
daqSession.IsContinuous = 0;
daqSession.DurationInSeconds = 1800;
daqSession.Channels(1).BridgeMode = ‘Full’;
daqSession.Channels(1).ExcitationVoltage = 5;
daqSession.Channels(1).NominalBridgeResistance = 1;
daqSession.Channels(1).Name = ‘Kulite 1’;
daqSession.Channels(2).BridgeMode = ‘Full’;
daqSession.Channels(2).NominalBridgeResistance = 1;
daqSession.Channels(2).Name = ‘Kulite2’;
daqSession.Channels(3).BridgeMode = ‘Full’;
daqSession.Channels(3).NominalBridgeResistance = 1;
daqSession.Channels(3).Name = ‘Kulite3’;
daqSession.Channels(4).BridgeMode = ‘Full’;
daqSession.Channels(4).NominalBridgeResistance = 1;
daqSession.Channels(4).Name = ‘Kulite4’;
%Read supplied voltage
V=daqSession.Channels(1).ExcitationVoltage;
%% Run the data acquisition session
[data,time] = daqSession.startForeground();
figure
plot(time,data)
%Take values from DAQ Matrix
V1=data(:,1);
V2=data(:,2);
V3=data(:,3);
V4=data(:,4);
%Create Matrix for other Time and Pressure Values
Voltagedata=[time,V1,V2,V3,V4];
fileName = sprintf(‘RawVData_%s.csv’, datestr(now, ‘yyyymmdd_HHMMSS’))
writematrix(Voltagedata,fileName)
%% Disconnect from the device
daqSession.release();
delete(daqSession);
clear daqSession; Hello,
I am building a data aquisition program using NI devices. I developed a program using the data aquisition toolbox, however the code that I have needs a run time as input which is only when I know the data aquisition time.
However in cases when I need to stop the data aquisition before the set input time, I am unable to do so before the complete run is done.
Is there a way to stop the program and still have access to the aquired data because if I stop the program, the workspace clears out and there in no data there or is there a way I can continously add data into a buffer which the data is being read so that even if the program is stipped, the aquired data is accessible.
I have attached my code for review.
close all
clear all
clc
%% Create a data acquisition session
daqSession = daq.createSession(‘ni’);
%% Add channels specified by subsystem type and device
daqSession.addAnalogInputChannel(‘Dev1′,’ai0′,’Bridge’);
daqSession.addAnalogInputChannel(‘Dev1′,’ai1′,’Bridge’);
daqSession.addAnalogInputChannel(‘Dev1′,’ai2′,’Bridge’);
daqSession.addAnalogInputChannel(‘Dev1′,’ai3′,’Bridge’);
%% Configure properties
daqSession.Rate = 1653;
daqSession.IsContinuous = 1;
hlistener = daqSession.addlistener(‘DataAvailable’,@(src,event) plot(event.TimeStamps, event.Data));
daqSession.IsContinuous = 0;
daqSession.DurationInSeconds = 1800;
daqSession.Channels(1).BridgeMode = ‘Full’;
daqSession.Channels(1).ExcitationVoltage = 5;
daqSession.Channels(1).NominalBridgeResistance = 1;
daqSession.Channels(1).Name = ‘Kulite 1’;
daqSession.Channels(2).BridgeMode = ‘Full’;
daqSession.Channels(2).NominalBridgeResistance = 1;
daqSession.Channels(2).Name = ‘Kulite2’;
daqSession.Channels(3).BridgeMode = ‘Full’;
daqSession.Channels(3).NominalBridgeResistance = 1;
daqSession.Channels(3).Name = ‘Kulite3’;
daqSession.Channels(4).BridgeMode = ‘Full’;
daqSession.Channels(4).NominalBridgeResistance = 1;
daqSession.Channels(4).Name = ‘Kulite4’;
%Read supplied voltage
V=daqSession.Channels(1).ExcitationVoltage;
%% Run the data acquisition session
[data,time] = daqSession.startForeground();
figure
plot(time,data)
%Take values from DAQ Matrix
V1=data(:,1);
V2=data(:,2);
V3=data(:,3);
V4=data(:,4);
%Create Matrix for other Time and Pressure Values
Voltagedata=[time,V1,V2,V3,V4];
fileName = sprintf(‘RawVData_%s.csv’, datestr(now, ‘yyyymmdd_HHMMSS’))
writematrix(Voltagedata,fileName)
%% Disconnect from the device
daqSession.release();
delete(daqSession);
clear daqSession; nidaq, data acquisition MATLAB Answers — New Questions
Multivariate regression for constrained dependent variables
I have a database formed by 6 independent variables and 2 dependent variables. The equation for each dependent variable should be something like:
I want to find s that satisfy .
Which metodology should I use?
I tried using mvregress, but I couldn’t constrain the dependent variables. I am also thinking of using optimization as well, but I still couldn’t figure out how to constrain the dependent variables.
Thank you so much!I have a database formed by 6 independent variables and 2 dependent variables. The equation for each dependent variable should be something like:
I want to find s that satisfy .
Which metodology should I use?
I tried using mvregress, but I couldn’t constrain the dependent variables. I am also thinking of using optimization as well, but I still couldn’t figure out how to constrain the dependent variables.
Thank you so much! I have a database formed by 6 independent variables and 2 dependent variables. The equation for each dependent variable should be something like:
I want to find s that satisfy .
Which metodology should I use?
I tried using mvregress, but I couldn’t constrain the dependent variables. I am also thinking of using optimization as well, but I still couldn’t figure out how to constrain the dependent variables.
Thank you so much! regression, optimization MATLAB Answers — New Questions
Write code to solve the following 0-1 Knapsack problem
Given a knapsack of items N and capacity W. The volume and value of the item is c(i) and w(i) respectively. Find the maximum total value in the knapsack. Suppose that N=10, and V=300. The volume of each item is 95, 75, 23, 73, 50, 22, 6, 57, 89 and 98. The values of each item are 89, 59, 19, 43, 100, 72, 44, 16, 7 and 64.Given a knapsack of items N and capacity W. The volume and value of the item is c(i) and w(i) respectively. Find the maximum total value in the knapsack. Suppose that N=10, and V=300. The volume of each item is 95, 75, 23, 73, 50, 22, 6, 57, 89 and 98. The values of each item are 89, 59, 19, 43, 100, 72, 44, 16, 7 and 64. Given a knapsack of items N and capacity W. The volume and value of the item is c(i) and w(i) respectively. Find the maximum total value in the knapsack. Suppose that N=10, and V=300. The volume of each item is 95, 75, 23, 73, 50, 22, 6, 57, 89 and 98. The values of each item are 89, 59, 19, 43, 100, 72, 44, 16, 7 and 64. knapsack0-1, find maximum total value MATLAB Answers — New Questions
Ignored/Incorrect MV constraint in nonlinear MPC block with parameter
Hello! I am implementing a nonlinear model predictive controller using MPC Toolbox in Simulink. A constraint of my NMPC appears to be ignored and I believe it is due to an error in my custon inequality constraint function. Here’s some context:
I am making a mass follow a reference displacement in a vehicle active suspension system. Currently, my NMPC’s manipulated variable is the increment in force for an actuator. My system under control takes a force magnitude as an input rather than an increment in force. Therefore, to constrain the maximum force magnitude allowed in my custom constraint function I need to pass in the previous magnitude as a parameter to add to the manipulated variable. This allows me to compare the sum of the increment and the previous magnitude to the constraint parameter. Currently, when looking at the produced force in a scope after a simulation, the amount is outside of the bounds of Fc_max and Fc_min (+/- 15N).
I have ensured the scope determines the value of the force magnitude correctly, and I have also ensured my cost function, state function, and equality constraints are configured properly. The bus that passes in params is also configured correctly. The controller exhibits acceptable tracking performance, it just ignores this constraint. Furthermore, the other constraints appear to be observed (but this could just be due to my reference not requiring the controller to apply those constraints). This leads me to believe my cineq function is incorrect somehow. The first block of code is my nlmpc setup, and the second is my cineq function. The picture is the force command produced (that violates the constraint).
%% cost function weights (best perf @ w=95000,w_dot=105,R=2,’E=1′)
Ts = 0.01;
Q_n = 1000;
Q_ndot = 0; % fix this
R = 15;
E = 1;
%% physical constraints
% maximum forces (currently +/- 15) (units: N)
Fc_max = 15;
Fc_min = -15;
% maximum rate of change in forces (units: N/Ts) (at Ts = 0.01 this is 10)
delta_Fc_max = 1000*Ts;
delta_Fc_min =-1000*Ts;
% maximum displacement of the spacing (units: m)
n_max = 0.05;
n_min = -0.05;
%% misc params
alpha_o = 1/(ms) + 1/(mu);
eta_ddot = 0;
Fc_last = 0;
Hc = 1;
%% NMPC settings, weights, and constraints
nx = 2;
ny = nx;
nu = 1;
nulmpcobj = nlmpc(nx,ny,nu);
nulmpcobj.Ts = Ts;
nulmpcobj.PredictionHorizon = 20;
nulmpcobj.ControlHorizon = Hc;
% how plant states evolve over time. Model is DT.
nulmpcobj.Model.StateFcn = "stateFunction";
nulmpcobj.Model.IsContinuousTime = false;
nulmpcobj.Model.NumberOfParameters = 15;
nulmpcobj.Model.OutputFcn = "outputFunction";
% set up cost function and constraints
nulmpcobj.Optimization.CustomCostFcn = "costFunction";
Optimization.CustomEqConFcn = "eqConFunction";
Optimization.CustomIneqConFcn = "ineqConFunction";
nulmpcobj.Optimization.ReplaceStandardCost = true;
SolverOptions.Algorithm = ‘sqp’;
% initial conditions
x0 = [0;0];
u0 = 0;
%% WARNING: EVERY TIME THIS IS EDITED, YOU NEED TO EDIT ALL OTHER FUNCTIONS WITH PARAMS…
parameters = {alpha_o,eta_ddot,Q_n,Q_ndot,R,E,Fc_max,Fc_min,delta_Fc_max,delta_Fc_min,n_max,n_min,Ts,Fc_last,Hc};
% Set up parameter bus for NMPC object (if it isn’t already initialized)
if exist(‘paramBus’,’var’)==0
mdl = ‘NULMPC_RAS’;
open_system(mdl)
createParameterBus(nulmpcobj,[mdl ‘/NULMPC’],’paramBus’,parameters);
end
%% Now the NLMPC and simulation parameters are ready to go!
%% Run the simulation or optionally validate the NMPC functions here in MATLAB.
% rng(0);
% validateFcns(nulmpcobj,rand(nx,1),rand(nu,1),[],parameters);
sim(mdl);
function cineq = ineqConFunction(X,U,data,alpha_o,eta_ddot,Q_n,Q_ndot,R,E,Fc_max,Fc_min,delta_Fc_max,delta_Fc_min,n_max,n_min,Ts,Fc_last,Hc)
cineq = zeros(6,1);
p = data.PredictionHorizon;
% delta constraint max/min
U1 = U(1:Hc,data.MVIndex(1));
cineq(1) = U1 – delta_Fc_max;
cineq(2) = -U1 + delta_Fc_min;
% magnitude
X1 = X(2:p+1,1);
cineq(3) = X1 – n_max;
cineq(4) = -X1 + n_min;
%% output constraint (THIS IS THE ONE I THINK IS INCORRECT)
cineq(5) = (U1 + Fc_last) – Fc_max;
cineq(6) = -(U1 + Fc_last) + Fc_min;
end
Since my control horizon is 1, the nmpc controller will hold my constrained input constant after the end of Hc. This should mean I do not need to have these constraints run across the whole prediction horizon p for the constraints to apply. Thank you to anyone who responds!Hello! I am implementing a nonlinear model predictive controller using MPC Toolbox in Simulink. A constraint of my NMPC appears to be ignored and I believe it is due to an error in my custon inequality constraint function. Here’s some context:
I am making a mass follow a reference displacement in a vehicle active suspension system. Currently, my NMPC’s manipulated variable is the increment in force for an actuator. My system under control takes a force magnitude as an input rather than an increment in force. Therefore, to constrain the maximum force magnitude allowed in my custom constraint function I need to pass in the previous magnitude as a parameter to add to the manipulated variable. This allows me to compare the sum of the increment and the previous magnitude to the constraint parameter. Currently, when looking at the produced force in a scope after a simulation, the amount is outside of the bounds of Fc_max and Fc_min (+/- 15N).
I have ensured the scope determines the value of the force magnitude correctly, and I have also ensured my cost function, state function, and equality constraints are configured properly. The bus that passes in params is also configured correctly. The controller exhibits acceptable tracking performance, it just ignores this constraint. Furthermore, the other constraints appear to be observed (but this could just be due to my reference not requiring the controller to apply those constraints). This leads me to believe my cineq function is incorrect somehow. The first block of code is my nlmpc setup, and the second is my cineq function. The picture is the force command produced (that violates the constraint).
%% cost function weights (best perf @ w=95000,w_dot=105,R=2,’E=1′)
Ts = 0.01;
Q_n = 1000;
Q_ndot = 0; % fix this
R = 15;
E = 1;
%% physical constraints
% maximum forces (currently +/- 15) (units: N)
Fc_max = 15;
Fc_min = -15;
% maximum rate of change in forces (units: N/Ts) (at Ts = 0.01 this is 10)
delta_Fc_max = 1000*Ts;
delta_Fc_min =-1000*Ts;
% maximum displacement of the spacing (units: m)
n_max = 0.05;
n_min = -0.05;
%% misc params
alpha_o = 1/(ms) + 1/(mu);
eta_ddot = 0;
Fc_last = 0;
Hc = 1;
%% NMPC settings, weights, and constraints
nx = 2;
ny = nx;
nu = 1;
nulmpcobj = nlmpc(nx,ny,nu);
nulmpcobj.Ts = Ts;
nulmpcobj.PredictionHorizon = 20;
nulmpcobj.ControlHorizon = Hc;
% how plant states evolve over time. Model is DT.
nulmpcobj.Model.StateFcn = "stateFunction";
nulmpcobj.Model.IsContinuousTime = false;
nulmpcobj.Model.NumberOfParameters = 15;
nulmpcobj.Model.OutputFcn = "outputFunction";
% set up cost function and constraints
nulmpcobj.Optimization.CustomCostFcn = "costFunction";
Optimization.CustomEqConFcn = "eqConFunction";
Optimization.CustomIneqConFcn = "ineqConFunction";
nulmpcobj.Optimization.ReplaceStandardCost = true;
SolverOptions.Algorithm = ‘sqp’;
% initial conditions
x0 = [0;0];
u0 = 0;
%% WARNING: EVERY TIME THIS IS EDITED, YOU NEED TO EDIT ALL OTHER FUNCTIONS WITH PARAMS…
parameters = {alpha_o,eta_ddot,Q_n,Q_ndot,R,E,Fc_max,Fc_min,delta_Fc_max,delta_Fc_min,n_max,n_min,Ts,Fc_last,Hc};
% Set up parameter bus for NMPC object (if it isn’t already initialized)
if exist(‘paramBus’,’var’)==0
mdl = ‘NULMPC_RAS’;
open_system(mdl)
createParameterBus(nulmpcobj,[mdl ‘/NULMPC’],’paramBus’,parameters);
end
%% Now the NLMPC and simulation parameters are ready to go!
%% Run the simulation or optionally validate the NMPC functions here in MATLAB.
% rng(0);
% validateFcns(nulmpcobj,rand(nx,1),rand(nu,1),[],parameters);
sim(mdl);
function cineq = ineqConFunction(X,U,data,alpha_o,eta_ddot,Q_n,Q_ndot,R,E,Fc_max,Fc_min,delta_Fc_max,delta_Fc_min,n_max,n_min,Ts,Fc_last,Hc)
cineq = zeros(6,1);
p = data.PredictionHorizon;
% delta constraint max/min
U1 = U(1:Hc,data.MVIndex(1));
cineq(1) = U1 – delta_Fc_max;
cineq(2) = -U1 + delta_Fc_min;
% magnitude
X1 = X(2:p+1,1);
cineq(3) = X1 – n_max;
cineq(4) = -X1 + n_min;
%% output constraint (THIS IS THE ONE I THINK IS INCORRECT)
cineq(5) = (U1 + Fc_last) – Fc_max;
cineq(6) = -(U1 + Fc_last) + Fc_min;
end
Since my control horizon is 1, the nmpc controller will hold my constrained input constant after the end of Hc. This should mean I do not need to have these constraints run across the whole prediction horizon p for the constraints to apply. Thank you to anyone who responds! Hello! I am implementing a nonlinear model predictive controller using MPC Toolbox in Simulink. A constraint of my NMPC appears to be ignored and I believe it is due to an error in my custon inequality constraint function. Here’s some context:
I am making a mass follow a reference displacement in a vehicle active suspension system. Currently, my NMPC’s manipulated variable is the increment in force for an actuator. My system under control takes a force magnitude as an input rather than an increment in force. Therefore, to constrain the maximum force magnitude allowed in my custom constraint function I need to pass in the previous magnitude as a parameter to add to the manipulated variable. This allows me to compare the sum of the increment and the previous magnitude to the constraint parameter. Currently, when looking at the produced force in a scope after a simulation, the amount is outside of the bounds of Fc_max and Fc_min (+/- 15N).
I have ensured the scope determines the value of the force magnitude correctly, and I have also ensured my cost function, state function, and equality constraints are configured properly. The bus that passes in params is also configured correctly. The controller exhibits acceptable tracking performance, it just ignores this constraint. Furthermore, the other constraints appear to be observed (but this could just be due to my reference not requiring the controller to apply those constraints). This leads me to believe my cineq function is incorrect somehow. The first block of code is my nlmpc setup, and the second is my cineq function. The picture is the force command produced (that violates the constraint).
%% cost function weights (best perf @ w=95000,w_dot=105,R=2,’E=1′)
Ts = 0.01;
Q_n = 1000;
Q_ndot = 0; % fix this
R = 15;
E = 1;
%% physical constraints
% maximum forces (currently +/- 15) (units: N)
Fc_max = 15;
Fc_min = -15;
% maximum rate of change in forces (units: N/Ts) (at Ts = 0.01 this is 10)
delta_Fc_max = 1000*Ts;
delta_Fc_min =-1000*Ts;
% maximum displacement of the spacing (units: m)
n_max = 0.05;
n_min = -0.05;
%% misc params
alpha_o = 1/(ms) + 1/(mu);
eta_ddot = 0;
Fc_last = 0;
Hc = 1;
%% NMPC settings, weights, and constraints
nx = 2;
ny = nx;
nu = 1;
nulmpcobj = nlmpc(nx,ny,nu);
nulmpcobj.Ts = Ts;
nulmpcobj.PredictionHorizon = 20;
nulmpcobj.ControlHorizon = Hc;
% how plant states evolve over time. Model is DT.
nulmpcobj.Model.StateFcn = "stateFunction";
nulmpcobj.Model.IsContinuousTime = false;
nulmpcobj.Model.NumberOfParameters = 15;
nulmpcobj.Model.OutputFcn = "outputFunction";
% set up cost function and constraints
nulmpcobj.Optimization.CustomCostFcn = "costFunction";
Optimization.CustomEqConFcn = "eqConFunction";
Optimization.CustomIneqConFcn = "ineqConFunction";
nulmpcobj.Optimization.ReplaceStandardCost = true;
SolverOptions.Algorithm = ‘sqp’;
% initial conditions
x0 = [0;0];
u0 = 0;
%% WARNING: EVERY TIME THIS IS EDITED, YOU NEED TO EDIT ALL OTHER FUNCTIONS WITH PARAMS…
parameters = {alpha_o,eta_ddot,Q_n,Q_ndot,R,E,Fc_max,Fc_min,delta_Fc_max,delta_Fc_min,n_max,n_min,Ts,Fc_last,Hc};
% Set up parameter bus for NMPC object (if it isn’t already initialized)
if exist(‘paramBus’,’var’)==0
mdl = ‘NULMPC_RAS’;
open_system(mdl)
createParameterBus(nulmpcobj,[mdl ‘/NULMPC’],’paramBus’,parameters);
end
%% Now the NLMPC and simulation parameters are ready to go!
%% Run the simulation or optionally validate the NMPC functions here in MATLAB.
% rng(0);
% validateFcns(nulmpcobj,rand(nx,1),rand(nu,1),[],parameters);
sim(mdl);
function cineq = ineqConFunction(X,U,data,alpha_o,eta_ddot,Q_n,Q_ndot,R,E,Fc_max,Fc_min,delta_Fc_max,delta_Fc_min,n_max,n_min,Ts,Fc_last,Hc)
cineq = zeros(6,1);
p = data.PredictionHorizon;
% delta constraint max/min
U1 = U(1:Hc,data.MVIndex(1));
cineq(1) = U1 – delta_Fc_max;
cineq(2) = -U1 + delta_Fc_min;
% magnitude
X1 = X(2:p+1,1);
cineq(3) = X1 – n_max;
cineq(4) = -X1 + n_min;
%% output constraint (THIS IS THE ONE I THINK IS INCORRECT)
cineq(5) = (U1 + Fc_last) – Fc_max;
cineq(6) = -(U1 + Fc_last) + Fc_min;
end
Since my control horizon is 1, the nmpc controller will hold my constrained input constant after the end of Hc. This should mean I do not need to have these constraints run across the whole prediction horizon p for the constraints to apply. Thank you to anyone who responds! nonlinear, mpc, constraint, simulink, nmpc, optimization MATLAB Answers — New Questions
Figure scaling issues in Linux
Getting good DPI settings for the editor in Linux is possible, though a tad annoying.
However, I have no idea how to go about fixing the scaling problems for figures. I can make a temp fix by upping the font size (see image) but can’t find a way to fix this. Ideally, want I want is to, by default, scale all images by about 160%.
Font adjusted with
set(findall(gcf,’-property’,’FontSize’),’FontSize’,18)
I could possible go through everything in
get(groot,’factory’)
and asjust dozens of settings there to fix this but realy all it needs is a single scale factor that would apply to fonts and data points/lines.
Cheers for any help.Getting good DPI settings for the editor in Linux is possible, though a tad annoying.
However, I have no idea how to go about fixing the scaling problems for figures. I can make a temp fix by upping the font size (see image) but can’t find a way to fix this. Ideally, want I want is to, by default, scale all images by about 160%.
Font adjusted with
set(findall(gcf,’-property’,’FontSize’),’FontSize’,18)
I could possible go through everything in
get(groot,’factory’)
and asjust dozens of settings there to fix this but realy all it needs is a single scale factor that would apply to fonts and data points/lines.
Cheers for any help. Getting good DPI settings for the editor in Linux is possible, though a tad annoying.
However, I have no idea how to go about fixing the scaling problems for figures. I can make a temp fix by upping the font size (see image) but can’t find a way to fix this. Ideally, want I want is to, by default, scale all images by about 160%.
Font adjusted with
set(findall(gcf,’-property’,’FontSize’),’FontSize’,18)
I could possible go through everything in
get(groot,’factory’)
and asjust dozens of settings there to fix this but realy all it needs is a single scale factor that would apply to fonts and data points/lines.
Cheers for any help. linux, dpi, scale, figures, dispaly MATLAB Answers — New Questions
How to export images to a single pdf file
Hi
I have a cell array and in it i have say 200 images of size(250,250). Now i want to generate a visualization i-e i want to generate a pdf file that will have all those 200 images in a single pdf file. Can someone please give a hint or guide me because i cant seem to find a possible solution by using print function.
Thanks anywaysHi
I have a cell array and in it i have say 200 images of size(250,250). Now i want to generate a visualization i-e i want to generate a pdf file that will have all those 200 images in a single pdf file. Can someone please give a hint or guide me because i cant seem to find a possible solution by using print function.
Thanks anyways Hi
I have a cell array and in it i have say 200 images of size(250,250). Now i want to generate a visualization i-e i want to generate a pdf file that will have all those 200 images in a single pdf file. Can someone please give a hint or guide me because i cant seem to find a possible solution by using print function.
Thanks anyways digital image processing, image processing, print, pdf MATLAB Answers — New Questions
How do I modify the attributes of entities in a custom matlab discrete-event system block?
I want to modify the entity attribute during the simulation in a custom matlab discrete-event system block.As shown below. But when I debugged the simulation, it turned out that the attribute of entity was restored to its original value after the program jumped out of the function that changed its value. How can I modify the attributes correctly?I want to modify the entity attribute during the simulation in a custom matlab discrete-event system block.As shown below. But when I debugged the simulation, it turned out that the attribute of entity was restored to its original value after the program jumped out of the function that changed its value. How can I modify the attributes correctly? I want to modify the entity attribute during the simulation in a custom matlab discrete-event system block.As shown below. But when I debugged the simulation, it turned out that the attribute of entity was restored to its original value after the program jumped out of the function that changed its value. How can I modify the attributes correctly? simulink, simevents, simulation MATLAB Answers — New Questions
CPU usage 100% when I use simulink desktop real time, both in connected mode and kernel mode
My sotfware and hardware infomation:
Simulink Desktop Real-Time version 23.2.0 (C) The MathWorks, Inc. 1994-2023
Matlab version is R2023b, and my CPU is Intel 13900H
I use simulink desktop real time to run my project, the fixed step is 0.1s, Once I start the model simulation, regardless of kernel mode or connected mode, my computer’s cpu usage is always dead at 100% unless I stop the model simulation; at first I suspected that it’s a problem with my model or time step, so I switched to the official matlab example (openExample(‘sldrt/ RealTimeVanDerPolSimulationExample’)), the result is still the same as my model simulation, the cpu usage stays at 100% unless I stop the model simulation for the cpu usage to return to normal.
Please help, thanksMy sotfware and hardware infomation:
Simulink Desktop Real-Time version 23.2.0 (C) The MathWorks, Inc. 1994-2023
Matlab version is R2023b, and my CPU is Intel 13900H
I use simulink desktop real time to run my project, the fixed step is 0.1s, Once I start the model simulation, regardless of kernel mode or connected mode, my computer’s cpu usage is always dead at 100% unless I stop the model simulation; at first I suspected that it’s a problem with my model or time step, so I switched to the official matlab example (openExample(‘sldrt/ RealTimeVanDerPolSimulationExample’)), the result is still the same as my model simulation, the cpu usage stays at 100% unless I stop the model simulation for the cpu usage to return to normal.
Please help, thanks My sotfware and hardware infomation:
Simulink Desktop Real-Time version 23.2.0 (C) The MathWorks, Inc. 1994-2023
Matlab version is R2023b, and my CPU is Intel 13900H
I use simulink desktop real time to run my project, the fixed step is 0.1s, Once I start the model simulation, regardless of kernel mode or connected mode, my computer’s cpu usage is always dead at 100% unless I stop the model simulation; at first I suspected that it’s a problem with my model or time step, so I switched to the official matlab example (openExample(‘sldrt/ RealTimeVanDerPolSimulationExample’)), the result is still the same as my model simulation, the cpu usage stays at 100% unless I stop the model simulation for the cpu usage to return to normal.
Please help, thanks desktop real time, cpu 100%, simulink MATLAB Answers — New Questions
confusion matrix from the classification learner app.
how can i calculate metrics from the trained model with classification learnerhow can i calculate metrics from the trained model with classification learner how can i calculate metrics from the trained model with classification learner matlab, classification, classification learner, confusion matrix, sensitivity, precision, metrics MATLAB Answers — New Questions
Error with find Function in MATLAB: “Incorrect number or types of inputs or outputs”
Hello,
I am encountering an error in MATLAB when using the find function in my code. The error message is:
Error using find Incorrect number or types of inputs or outputs for function ‘find’.
The error occurs in the following function:
function SNR_matrix = Compute_SNR(K, N, M, A, z,…);
SNR_matrix = optimexpr(K, N, M);
for v = 1:M
for s = 1:K
for n = 1:N
Arg1 = find(A(s, :, v), 1); % This line causes the error
% [Additional code here]
end
end
end
end
and ”A” is a Binary decision variable
A = optimvar(‘A’, K, N, M, ‘Type’, ‘integer’, ‘LowerBound’, 0, ‘UpperBound’, 1);
How can I resolve this error? Are there specific issues with how find is used with multi-dimensional arrays? What adjustments should I make to ensure that the find function works correctly in this context?
Any Help will be appreciated.
Thanks in advance!Hello,
I am encountering an error in MATLAB when using the find function in my code. The error message is:
Error using find Incorrect number or types of inputs or outputs for function ‘find’.
The error occurs in the following function:
function SNR_matrix = Compute_SNR(K, N, M, A, z,…);
SNR_matrix = optimexpr(K, N, M);
for v = 1:M
for s = 1:K
for n = 1:N
Arg1 = find(A(s, :, v), 1); % This line causes the error
% [Additional code here]
end
end
end
end
and ”A” is a Binary decision variable
A = optimvar(‘A’, K, N, M, ‘Type’, ‘integer’, ‘LowerBound’, 0, ‘UpperBound’, 1);
How can I resolve this error? Are there specific issues with how find is used with multi-dimensional arrays? What adjustments should I make to ensure that the find function works correctly in this context?
Any Help will be appreciated.
Thanks in advance! Hello,
I am encountering an error in MATLAB when using the find function in my code. The error message is:
Error using find Incorrect number or types of inputs or outputs for function ‘find’.
The error occurs in the following function:
function SNR_matrix = Compute_SNR(K, N, M, A, z,…);
SNR_matrix = optimexpr(K, N, M);
for v = 1:M
for s = 1:K
for n = 1:N
Arg1 = find(A(s, :, v), 1); % This line causes the error
% [Additional code here]
end
end
end
end
and ”A” is a Binary decision variable
A = optimvar(‘A’, K, N, M, ‘Type’, ‘integer’, ‘LowerBound’, 0, ‘UpperBound’, 1);
How can I resolve this error? Are there specific issues with how find is used with multi-dimensional arrays? What adjustments should I make to ensure that the find function works correctly in this context?
Any Help will be appreciated.
Thanks in advance! error, matlab code, find, function, optimization MATLAB Answers — New Questions
convert mat file to excel
how can i convert a mat file into an excel filehow can i convert a mat file into an excel file how can i convert a mat file into an excel file files, matlab MATLAB Answers — New Questions