Tag Archives: matlab
Different behavior creating private temporary tables with MATLAB execute vs Oracle SQL Developer
I am a mechanical engineer working with manufacturing factory data from an Oracle database (via ODBC). My predecessors used a large quantity of specialty SQL scripts and query statements written by the database team, but I have replaced many of them with far fewer MATLAB functions.
The final (and largest) piece of the legacy scripts involve creating temporary tables. (Please do not suggest converting into with statements; the database is much more complicated than I’m showing.) My credentials to this database permit me to create private temporary tables. I can successfully create and fetch from these tables with Oracle SQL Developer using the patterns below.
Create
% — EXAMPLE CREATE STATEMENT IN MATLAB M-FILE
% CREATE PRIVATE TEMPORARY TABLE ORA$PTT_MY_RESULTS AS (
% SELECT [COLUMNS]
% FROM SOME_TABLE
% WHERE [FILTERING CLAUSES]
% );
Fetch
% — EXAMPLE SELECT STATEMENT IN MATLAB M-FILE
% SELECT * FROM ORA$PTT_MY_RESULTS
When I execute the same create statements in MATLAB, nothing seems to happen. Fetch fails indicating the table or view does not exist.
oracle_db = database( …
name_oracle_db, …
my_username, …
my_password …
,’AutoCommit’,’on’ …
,’ReadOnly’,’off’);
oracle_db.execute(my_create_statement);
%{
oracle_db.execute(my_create_statement);
% ^ should’ve caused an error that the table exists.
%}
%{
oracle_db.commit();
% ^ no effect.
%}
% my_results = oracle_db.sqlread( "ORA$PTT_MY_RESULTS");
% my_results = oracle_db.select("SELECT * FROM ORA$PTT_MY_RESULTS");
% my_results = oracle_db.fetch( "SELECT * FROM ORA$PTT_MY_RESULTS");
% % ^ table or view does not exist
What are the differences between MATLAB and Oracle SQL Developer when executing the creation of a private temporary table? Standard select statements work exactly the same between MATLAB’s fetch/select methods and Oracle SQL Developer. MATLAB’s execute method does not seem to create the tables.
NOTE: This difference was detected early earlier in the week, before CrowdStrike took down everything.I am a mechanical engineer working with manufacturing factory data from an Oracle database (via ODBC). My predecessors used a large quantity of specialty SQL scripts and query statements written by the database team, but I have replaced many of them with far fewer MATLAB functions.
The final (and largest) piece of the legacy scripts involve creating temporary tables. (Please do not suggest converting into with statements; the database is much more complicated than I’m showing.) My credentials to this database permit me to create private temporary tables. I can successfully create and fetch from these tables with Oracle SQL Developer using the patterns below.
Create
% — EXAMPLE CREATE STATEMENT IN MATLAB M-FILE
% CREATE PRIVATE TEMPORARY TABLE ORA$PTT_MY_RESULTS AS (
% SELECT [COLUMNS]
% FROM SOME_TABLE
% WHERE [FILTERING CLAUSES]
% );
Fetch
% — EXAMPLE SELECT STATEMENT IN MATLAB M-FILE
% SELECT * FROM ORA$PTT_MY_RESULTS
When I execute the same create statements in MATLAB, nothing seems to happen. Fetch fails indicating the table or view does not exist.
oracle_db = database( …
name_oracle_db, …
my_username, …
my_password …
,’AutoCommit’,’on’ …
,’ReadOnly’,’off’);
oracle_db.execute(my_create_statement);
%{
oracle_db.execute(my_create_statement);
% ^ should’ve caused an error that the table exists.
%}
%{
oracle_db.commit();
% ^ no effect.
%}
% my_results = oracle_db.sqlread( "ORA$PTT_MY_RESULTS");
% my_results = oracle_db.select("SELECT * FROM ORA$PTT_MY_RESULTS");
% my_results = oracle_db.fetch( "SELECT * FROM ORA$PTT_MY_RESULTS");
% % ^ table or view does not exist
What are the differences between MATLAB and Oracle SQL Developer when executing the creation of a private temporary table? Standard select statements work exactly the same between MATLAB’s fetch/select methods and Oracle SQL Developer. MATLAB’s execute method does not seem to create the tables.
NOTE: This difference was detected early earlier in the week, before CrowdStrike took down everything. I am a mechanical engineer working with manufacturing factory data from an Oracle database (via ODBC). My predecessors used a large quantity of specialty SQL scripts and query statements written by the database team, but I have replaced many of them with far fewer MATLAB functions.
The final (and largest) piece of the legacy scripts involve creating temporary tables. (Please do not suggest converting into with statements; the database is much more complicated than I’m showing.) My credentials to this database permit me to create private temporary tables. I can successfully create and fetch from these tables with Oracle SQL Developer using the patterns below.
Create
% — EXAMPLE CREATE STATEMENT IN MATLAB M-FILE
% CREATE PRIVATE TEMPORARY TABLE ORA$PTT_MY_RESULTS AS (
% SELECT [COLUMNS]
% FROM SOME_TABLE
% WHERE [FILTERING CLAUSES]
% );
Fetch
% — EXAMPLE SELECT STATEMENT IN MATLAB M-FILE
% SELECT * FROM ORA$PTT_MY_RESULTS
When I execute the same create statements in MATLAB, nothing seems to happen. Fetch fails indicating the table or view does not exist.
oracle_db = database( …
name_oracle_db, …
my_username, …
my_password …
,’AutoCommit’,’on’ …
,’ReadOnly’,’off’);
oracle_db.execute(my_create_statement);
%{
oracle_db.execute(my_create_statement);
% ^ should’ve caused an error that the table exists.
%}
%{
oracle_db.commit();
% ^ no effect.
%}
% my_results = oracle_db.sqlread( "ORA$PTT_MY_RESULTS");
% my_results = oracle_db.select("SELECT * FROM ORA$PTT_MY_RESULTS");
% my_results = oracle_db.fetch( "SELECT * FROM ORA$PTT_MY_RESULTS");
% % ^ table or view does not exist
What are the differences between MATLAB and Oracle SQL Developer when executing the creation of a private temporary table? Standard select statements work exactly the same between MATLAB’s fetch/select methods and Oracle SQL Developer. MATLAB’s execute method does not seem to create the tables.
NOTE: This difference was detected early earlier in the week, before CrowdStrike took down everything. oracle, sql, execute, database MATLAB Answers — New Questions
Why do I get Empty Plots during Optimization?
Inspired by custom plotting given here, for one-dimensional design variable case, I would like to generalize it to n-dimensional case. I wrote following code to achieve that:
function state = gaPlotRangeND(options, state, flag)
% gaPlotRangeND Plots the mean and the range of the population for n-dimensions.
% STATE = gaPlotRangeND(OPTIONS, STATE, FLAG) plots the mean and the range
% (highest and the lowest) of individuals for each variable.
generation = state.Generation;
population = state.Population;
numVars = size(population, 2);
M = mean(population);
L = M – min(population);
U = max(population) – M;
switch flag
case ‘init’
for i = 1:numVars
subplot(numVars, 1, i);
set(gca, ‘xlim’, [1, options.MaxGenerations + 1]);
plotRange = errorbar(generation, M(:, i), L(:, i), U(:, i));
set(plotRange, ‘Tag’, [‘Var_’ num2str(i)]);
title([‘Range of Population, Mean for Variable ‘ num2str(i)], ‘interp’, ‘none’)
xlabel(‘Generation’, ‘interp’, ‘none’)
end
case ‘iter’
for i = 1:numVars
subplot(numVars, 1, i);
plotRange = findobj(get(gca, ‘Children’), ‘Tag’, [‘Var_’ num2str(i)]);
newX = [get(plotRange, ‘Xdata’), generation];
newY = [get(plotRange, ‘Ydata’), M(:, i)];
newL = [get(plotRange, ‘Ldata’), L(:, i)];
newU = [get(plotRange, ‘Udata’), U(:, i)];
set(plotRange, ‘Xdata’, newX, ‘Ydata’, newY, ‘Ldata’, newL, ‘Udata’, newU);
end
end
end
When I run it for a simple two-dimensional test problem defined below, it does not work. It just outputs two empty subplots on top of each other during execution of genetic algorithm, and ends with a single empty plot. It is supposed to plot mean and range of population at each iteration for each variable, which is two in this case.
function y = booth_func(x)
y = (x(1) + 2 * x(2) – 7) ^ 2 + (2 * x(1) + x(2) – 5) ^ 2;
end
options = optimoptions(‘ga’, ‘PlotFcn’, @gaPlotRangeND);
[x, fval] = ga(@booth_func, 2, [], [], [], [], [], [], [], options);
How can I solve this issue? What do I miss here?Inspired by custom plotting given here, for one-dimensional design variable case, I would like to generalize it to n-dimensional case. I wrote following code to achieve that:
function state = gaPlotRangeND(options, state, flag)
% gaPlotRangeND Plots the mean and the range of the population for n-dimensions.
% STATE = gaPlotRangeND(OPTIONS, STATE, FLAG) plots the mean and the range
% (highest and the lowest) of individuals for each variable.
generation = state.Generation;
population = state.Population;
numVars = size(population, 2);
M = mean(population);
L = M – min(population);
U = max(population) – M;
switch flag
case ‘init’
for i = 1:numVars
subplot(numVars, 1, i);
set(gca, ‘xlim’, [1, options.MaxGenerations + 1]);
plotRange = errorbar(generation, M(:, i), L(:, i), U(:, i));
set(plotRange, ‘Tag’, [‘Var_’ num2str(i)]);
title([‘Range of Population, Mean for Variable ‘ num2str(i)], ‘interp’, ‘none’)
xlabel(‘Generation’, ‘interp’, ‘none’)
end
case ‘iter’
for i = 1:numVars
subplot(numVars, 1, i);
plotRange = findobj(get(gca, ‘Children’), ‘Tag’, [‘Var_’ num2str(i)]);
newX = [get(plotRange, ‘Xdata’), generation];
newY = [get(plotRange, ‘Ydata’), M(:, i)];
newL = [get(plotRange, ‘Ldata’), L(:, i)];
newU = [get(plotRange, ‘Udata’), U(:, i)];
set(plotRange, ‘Xdata’, newX, ‘Ydata’, newY, ‘Ldata’, newL, ‘Udata’, newU);
end
end
end
When I run it for a simple two-dimensional test problem defined below, it does not work. It just outputs two empty subplots on top of each other during execution of genetic algorithm, and ends with a single empty plot. It is supposed to plot mean and range of population at each iteration for each variable, which is two in this case.
function y = booth_func(x)
y = (x(1) + 2 * x(2) – 7) ^ 2 + (2 * x(1) + x(2) – 5) ^ 2;
end
options = optimoptions(‘ga’, ‘PlotFcn’, @gaPlotRangeND);
[x, fval] = ga(@booth_func, 2, [], [], [], [], [], [], [], options);
How can I solve this issue? What do I miss here? Inspired by custom plotting given here, for one-dimensional design variable case, I would like to generalize it to n-dimensional case. I wrote following code to achieve that:
function state = gaPlotRangeND(options, state, flag)
% gaPlotRangeND Plots the mean and the range of the population for n-dimensions.
% STATE = gaPlotRangeND(OPTIONS, STATE, FLAG) plots the mean and the range
% (highest and the lowest) of individuals for each variable.
generation = state.Generation;
population = state.Population;
numVars = size(population, 2);
M = mean(population);
L = M – min(population);
U = max(population) – M;
switch flag
case ‘init’
for i = 1:numVars
subplot(numVars, 1, i);
set(gca, ‘xlim’, [1, options.MaxGenerations + 1]);
plotRange = errorbar(generation, M(:, i), L(:, i), U(:, i));
set(plotRange, ‘Tag’, [‘Var_’ num2str(i)]);
title([‘Range of Population, Mean for Variable ‘ num2str(i)], ‘interp’, ‘none’)
xlabel(‘Generation’, ‘interp’, ‘none’)
end
case ‘iter’
for i = 1:numVars
subplot(numVars, 1, i);
plotRange = findobj(get(gca, ‘Children’), ‘Tag’, [‘Var_’ num2str(i)]);
newX = [get(plotRange, ‘Xdata’), generation];
newY = [get(plotRange, ‘Ydata’), M(:, i)];
newL = [get(plotRange, ‘Ldata’), L(:, i)];
newU = [get(plotRange, ‘Udata’), U(:, i)];
set(plotRange, ‘Xdata’, newX, ‘Ydata’, newY, ‘Ldata’, newL, ‘Udata’, newU);
end
end
end
When I run it for a simple two-dimensional test problem defined below, it does not work. It just outputs two empty subplots on top of each other during execution of genetic algorithm, and ends with a single empty plot. It is supposed to plot mean and range of population at each iteration for each variable, which is two in this case.
function y = booth_func(x)
y = (x(1) + 2 * x(2) – 7) ^ 2 + (2 * x(1) + x(2) – 5) ^ 2;
end
options = optimoptions(‘ga’, ‘PlotFcn’, @gaPlotRangeND);
[x, fval] = ga(@booth_func, 2, [], [], [], [], [], [], [], options);
How can I solve this issue? What do I miss here? plotting, subplot, optimization MATLAB Answers — New Questions
How do i create the m-file for a simulink simulation of an induction machine in the stationary dq reference frame?
How do i create the m-file for a simulink simulation of an induction machine in the stationary dq reference frame?How do i create the m-file for a simulink simulation of an induction machine in the stationary dq reference frame? How do i create the m-file for a simulink simulation of an induction machine in the stationary dq reference frame? simulink, mathematics, induction motor MATLAB Answers — New Questions
variables not being saved?
I just included the code for U here, but neither L nor U are being saved, but they can both be displayed? I’m trying to use the values for L and U as inputs in another function, but it says "unrecognized variable"
function [L,U] = lumine(A)
%lumine: LU decomposition
%input:
%A = coefficient matrix
%output:
%L = lower matrix
%U = upper matrix
[m,n] = size(A); % defines m and n
if m~=n %checks to see if the matrix is square
error(‘Matrix A must be square’) % displays error if matrix is not square
end
if det(A) == 0 %checks to see if the matrix is singular
error(‘Matrix cannot be singular’)
end
% forward elimination
Afake = A;
for k = 1:n % starts at position 1, goes to the last column
for i = k+1:n %starts at the row after k, goes to the second to last row
factor = Afake(i,k)/Afake(k,k); %defines factor as the element directly below one of the elements in the diagonal, divided by that element on the diagonal
Afake(i,1:n) = Afake(i,1:n)-factor*Afake(k,1:n); %for each row of the matrix, the row before is multiplied by factor, which is then subtracted
end
end
U = Afake; % A becomes the upper matrix after every row is completed
EndI just included the code for U here, but neither L nor U are being saved, but they can both be displayed? I’m trying to use the values for L and U as inputs in another function, but it says "unrecognized variable"
function [L,U] = lumine(A)
%lumine: LU decomposition
%input:
%A = coefficient matrix
%output:
%L = lower matrix
%U = upper matrix
[m,n] = size(A); % defines m and n
if m~=n %checks to see if the matrix is square
error(‘Matrix A must be square’) % displays error if matrix is not square
end
if det(A) == 0 %checks to see if the matrix is singular
error(‘Matrix cannot be singular’)
end
% forward elimination
Afake = A;
for k = 1:n % starts at position 1, goes to the last column
for i = k+1:n %starts at the row after k, goes to the second to last row
factor = Afake(i,k)/Afake(k,k); %defines factor as the element directly below one of the elements in the diagonal, divided by that element on the diagonal
Afake(i,1:n) = Afake(i,1:n)-factor*Afake(k,1:n); %for each row of the matrix, the row before is multiplied by factor, which is then subtracted
end
end
U = Afake; % A becomes the upper matrix after every row is completed
End I just included the code for U here, but neither L nor U are being saved, but they can both be displayed? I’m trying to use the values for L and U as inputs in another function, but it says "unrecognized variable"
function [L,U] = lumine(A)
%lumine: LU decomposition
%input:
%A = coefficient matrix
%output:
%L = lower matrix
%U = upper matrix
[m,n] = size(A); % defines m and n
if m~=n %checks to see if the matrix is square
error(‘Matrix A must be square’) % displays error if matrix is not square
end
if det(A) == 0 %checks to see if the matrix is singular
error(‘Matrix cannot be singular’)
end
% forward elimination
Afake = A;
for k = 1:n % starts at position 1, goes to the last column
for i = k+1:n %starts at the row after k, goes to the second to last row
factor = Afake(i,k)/Afake(k,k); %defines factor as the element directly below one of the elements in the diagonal, divided by that element on the diagonal
Afake(i,1:n) = Afake(i,1:n)-factor*Afake(k,1:n); %for each row of the matrix, the row before is multiplied by factor, which is then subtracted
end
end
U = Afake; % A becomes the upper matrix after every row is completed
End variables MATLAB Answers — New Questions
error saying not enough input arguments?
function newmatrix = rootflow(conversion)
a = [-1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ; 1 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0; 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 .6 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 .253 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 .147 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 .16 0 0 -1 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 1 0 0 -1 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 .84 0 0 0 0 0 -1 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 ; 0 0 0 0 0 0 0 0 0 0 0 0 .09 0 0 -1 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 .94 0 0 -1 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 .91 0 0 0 0 0 -1 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 .06 0 0 0 0 0 -1 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1];
b = zeros(21,1);
b(1,1) = -1360.777;
a5 = a; %new variable for a so old one isn’t altered
newmatrix = zeros(1001,1); %creates matrix that I will add the values from the for loop
rowcounter = 1; %counts rows
for i = (conversion) %will go through all the conversion values
a5(7,4) = 1-i; %changes the values that are affected by the conversion
a5(8,4) = i*0.631;
a5(9,4) = i*0.368;
x5 = a5b; %new solution matrix for each conversion value
total_recycle_flowrate_5 = 2.20462*(x5(19) + x5(20));%new recycle flowrate for each conversion value
newmatrix(rowcounter) = total_recycle_flowrate_5;%the new recycle flowrate is added to newmatrix
rowcounter = rowcounter + 1; %rowcounter moves to next row so recylce flowrate will be added to next row
end
rootflow(0:.001:1)
>> rootflow
Not enough input arguments.
Error in rootflow (line 8)
for i = (conversion) %will go through all the conversion valuesfunction newmatrix = rootflow(conversion)
a = [-1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ; 1 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0; 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 .6 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 .253 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 .147 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 .16 0 0 -1 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 1 0 0 -1 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 .84 0 0 0 0 0 -1 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 ; 0 0 0 0 0 0 0 0 0 0 0 0 .09 0 0 -1 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 .94 0 0 -1 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 .91 0 0 0 0 0 -1 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 .06 0 0 0 0 0 -1 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1];
b = zeros(21,1);
b(1,1) = -1360.777;
a5 = a; %new variable for a so old one isn’t altered
newmatrix = zeros(1001,1); %creates matrix that I will add the values from the for loop
rowcounter = 1; %counts rows
for i = (conversion) %will go through all the conversion values
a5(7,4) = 1-i; %changes the values that are affected by the conversion
a5(8,4) = i*0.631;
a5(9,4) = i*0.368;
x5 = a5b; %new solution matrix for each conversion value
total_recycle_flowrate_5 = 2.20462*(x5(19) + x5(20));%new recycle flowrate for each conversion value
newmatrix(rowcounter) = total_recycle_flowrate_5;%the new recycle flowrate is added to newmatrix
rowcounter = rowcounter + 1; %rowcounter moves to next row so recylce flowrate will be added to next row
end
rootflow(0:.001:1)
>> rootflow
Not enough input arguments.
Error in rootflow (line 8)
for i = (conversion) %will go through all the conversion values function newmatrix = rootflow(conversion)
a = [-1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ; 1 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0; 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 .6 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 .253 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 .147 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 .16 0 0 -1 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 1 0 0 -1 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 .84 0 0 0 0 0 -1 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 ; 0 0 0 0 0 0 0 0 0 0 0 0 .09 0 0 -1 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 .94 0 0 -1 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 .91 0 0 0 0 0 -1 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 .06 0 0 0 0 0 -1 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1];
b = zeros(21,1);
b(1,1) = -1360.777;
a5 = a; %new variable for a so old one isn’t altered
newmatrix = zeros(1001,1); %creates matrix that I will add the values from the for loop
rowcounter = 1; %counts rows
for i = (conversion) %will go through all the conversion values
a5(7,4) = 1-i; %changes the values that are affected by the conversion
a5(8,4) = i*0.631;
a5(9,4) = i*0.368;
x5 = a5b; %new solution matrix for each conversion value
total_recycle_flowrate_5 = 2.20462*(x5(19) + x5(20));%new recycle flowrate for each conversion value
newmatrix(rowcounter) = total_recycle_flowrate_5;%the new recycle flowrate is added to newmatrix
rowcounter = rowcounter + 1; %rowcounter moves to next row so recylce flowrate will be added to next row
end
rootflow(0:.001:1)
>> rootflow
Not enough input arguments.
Error in rootflow (line 8)
for i = (conversion) %will go through all the conversion values function inputs MATLAB Answers — New Questions
finding the minimum of a function input with a parameter
%function to find recylce flowrate for range of conversions
%then trying to find minimum conversion where total_recylce_flowrate_5 <= 7000
function newmatrix = rootflow(conversion)
a = [-1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ; 1 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0; 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 .6 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 .253 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 .147 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 .16 0 0 -1 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 1 0 0 -1 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 .84 0 0 0 0 0 -1 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 ; 0 0 0 0 0 0 0 0 0 0 0 0 .09 0 0 -1 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 .94 0 0 -1 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 .91 0 0 0 0 0 -1 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 .06 0 0 0 0 0 -1 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1];
b = zeros(21,1);
b(1,1) = -1360.777;
a5 = a; %new variable for a so old one isn’t altered
newmatrix = zeros(1001,1); %creates matrix that I will add the values from the for loop
rowcounter = 1; %counts rows
for i = (conversion) %will go through all the conversion values
a5(7,4) = 1-i; %changes the values that are affected by the conversion
a5(8,4) = i*0.631;
a5(9,4) = i*0.368;
x5 = a5b; %new solution matrix for each conversion value
total_recycle_flowrate_5 = 2.20462*(x5(19) + x5(20));%new recycle flowrate for each conversion value
newmatrix(rowcounter) = total_recycle_flowrate_5;%the new recycle flowrate is added to newmatrix
rowcounter = rowcounter + 1; %rowcounter moves to next row so recylce flowrate will be added to next row
end
end
newmatrix = rootflow(0:.001:1)
%trying to minimize conversions, not rootflow, but it won’t let me? Also how to correctly use parameter (<=7000)?
fminsearch(rootflow(0:.001:1),.5,options)
options = optimset(total_recycle_flowrate_5,<=7000)%function to find recylce flowrate for range of conversions
%then trying to find minimum conversion where total_recylce_flowrate_5 <= 7000
function newmatrix = rootflow(conversion)
a = [-1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ; 1 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0; 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 .6 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 .253 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 .147 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 .16 0 0 -1 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 1 0 0 -1 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 .84 0 0 0 0 0 -1 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 ; 0 0 0 0 0 0 0 0 0 0 0 0 .09 0 0 -1 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 .94 0 0 -1 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 .91 0 0 0 0 0 -1 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 .06 0 0 0 0 0 -1 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1];
b = zeros(21,1);
b(1,1) = -1360.777;
a5 = a; %new variable for a so old one isn’t altered
newmatrix = zeros(1001,1); %creates matrix that I will add the values from the for loop
rowcounter = 1; %counts rows
for i = (conversion) %will go through all the conversion values
a5(7,4) = 1-i; %changes the values that are affected by the conversion
a5(8,4) = i*0.631;
a5(9,4) = i*0.368;
x5 = a5b; %new solution matrix for each conversion value
total_recycle_flowrate_5 = 2.20462*(x5(19) + x5(20));%new recycle flowrate for each conversion value
newmatrix(rowcounter) = total_recycle_flowrate_5;%the new recycle flowrate is added to newmatrix
rowcounter = rowcounter + 1; %rowcounter moves to next row so recylce flowrate will be added to next row
end
end
newmatrix = rootflow(0:.001:1)
%trying to minimize conversions, not rootflow, but it won’t let me? Also how to correctly use parameter (<=7000)?
fminsearch(rootflow(0:.001:1),.5,options)
options = optimset(total_recycle_flowrate_5,<=7000) %function to find recylce flowrate for range of conversions
%then trying to find minimum conversion where total_recylce_flowrate_5 <= 7000
function newmatrix = rootflow(conversion)
a = [-1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ; 1 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0; 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 .6 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 .253 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 1 0; 0 0 0 .147 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 .16 0 0 -1 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 1 0 0 -1 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 .84 0 0 0 0 0 -1 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 ; 0 0 0 0 0 0 0 0 0 0 0 0 .09 0 0 -1 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 .94 0 0 -1 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 .91 0 0 0 0 0 -1 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 .06 0 0 0 0 0 -1 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1];
b = zeros(21,1);
b(1,1) = -1360.777;
a5 = a; %new variable for a so old one isn’t altered
newmatrix = zeros(1001,1); %creates matrix that I will add the values from the for loop
rowcounter = 1; %counts rows
for i = (conversion) %will go through all the conversion values
a5(7,4) = 1-i; %changes the values that are affected by the conversion
a5(8,4) = i*0.631;
a5(9,4) = i*0.368;
x5 = a5b; %new solution matrix for each conversion value
total_recycle_flowrate_5 = 2.20462*(x5(19) + x5(20));%new recycle flowrate for each conversion value
newmatrix(rowcounter) = total_recycle_flowrate_5;%the new recycle flowrate is added to newmatrix
rowcounter = rowcounter + 1; %rowcounter moves to next row so recylce flowrate will be added to next row
end
end
newmatrix = rootflow(0:.001:1)
%trying to minimize conversions, not rootflow, but it won’t let me? Also how to correctly use parameter (<=7000)?
fminsearch(rootflow(0:.001:1),.5,options)
options = optimset(total_recycle_flowrate_5,<=7000) minimization MATLAB Answers — New Questions
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