Tag Archives: matlab
MATLAB-YALMIP optimal trendy program cannot converge
I use MATLAB-YALMIP to write the optimal trend program based on the IEEEE14 system, but I can’t converge. Please help to see if the program is wrong?
code:
% Optimal Power Flow Example
% Based on the IEEE 14-bus standard case (i.e., case14 in Matpower)
% Implemented in MATLAB with YALMIP
clear; clc;
% Load power system data
mpc = loadcase(‘case14’); % You can also load other data files, such as case9, case30, etc.
% Define variables and parameters
nb = size(mpc.bus, 1); % Number of buses (nodes)
nl = size(mpc.branch, 1); % Number of branches (lines)
ng = size(mpc.gen, 1); % Number of generators
nr = nb – ng; % Number of load buses
% Extract node data
bus_id = mpc.bus(:, 1); % Bus IDs
bus_type = mpc.bus(:, 2); % Bus types (1-PQ, 2-PV, 3-Slack)
Pd = mpc.bus(:, 3); % Active power demand (MW)
Qd = mpc.bus(:, 4); % Reactive power demand (MVAr)
Vmin = mpc.bus(:, 13); % Minimum bus voltage (p.u.)
Vmax = mpc.bus(:, 12); % Maximum bus voltage (p.u.)
% Extract generator data
gen_id = mpc.gen(:, 1); % Bus IDs where generators are connected
Pgmin = mpc.gen(:, 10); % Minimum generator active power output (MW)
Pgmax = mpc.gen(:, 9); % Maximum generator active power output (MW)
Qgmin = mpc.gen(:, 5); % Minimum generator reactive power output (MVAr)
Qgmax = mpc.gen(:, 4); % Maximum generator reactive power output (MVAr)
a2 = mpc.gencost(:, 5); % Generator cost curve coefficient for quadratic term
a1 = mpc.gencost(:, 6); % Generator cost curve coefficient for linear term
a0 = mpc.gencost(:, 7); % Generator cost curve constant term
% Extract branch data
fbus = mpc.branch(:, 1); % "From" bus (starting node) of each branch
tbus = mpc.branch(:, 2); % "To" bus (ending node) of each branch
Plmax = ones(nl, 1) * 4000; % Maximum branch active power flow limit (MW)
% Plmax = mpc.branch(:, 6) .* mpc.branch(:, 3) * 1e-3; % Maximum branch active power flow limit (MW)
% Calculate the bus admittance matrix
[Ybus, ~, ~] = makeYbus(mpc); % Use a Matpower function to calculate the bus admittance matrix
Gbus = real(Ybus); % Real part of bus admittance matrix (conductance)
Bbus = imag(Ybus); % Imaginary part of bus admittance matrix (susceptance)
% Define YALMIP variables
Pg = sdpvar(ng, 1, ‘full’); % Generator active power output variables
Qg = sdpvar(ng, 1, ‘full’); % Generator reactive power output variables
V = sdpvar(nb, 1, ‘full’); % Bus voltage magnitude variables
theta = sdpvar(nb, 1, ‘full’); % Bus voltage angle variables
Pl = sdpvar(nl, 1, ‘full’); % Branch active power flow variables
% Define the objective function
objective = sum(a2 .* Pg.^2 + a1 .* Pg + a0); % Minimize the total operating cost
% Define constraints
constraints = [];
% Node power balance constraints
for i = 1:nb
% Active power balance equation for node i
if ismember(i, gen_id)
record = find(gen_id == i);
constraints = [constraints, Pg(record) – Pd(i) – V(i) * sum(V * (Gbus(i, 🙂 * cos(theta(i) – theta) + Bbus(i, 🙂 * sin(theta(i) – theta))) == 0];
constraints = [constraints, Qg(record) – Qd(i) + V(i) * sum(V * (Gbus(i, 🙂 * sin(theta(i) – theta) – Bbus(i, 🙂 * cos(theta(i) – theta))) == 0];
else
constraints = [constraints, -Pd(i) – V(i) * sum(V * (Gbus(i, 🙂 * cos(theta(i) – theta) + Bbus(i, 🙂 * sin(theta(i) – theta))) == 0];
constraints = [constraints, -Qd(i) + V(i) * sum(V * (Gbus(i, 🙂 * sin(theta(i) – theta) – Bbus(i, 🙂 * cos(theta(i) – theta))) == 0];
end
end
% Generator output limit constraints
for i = 1:ng
% Minimum active power output constraint for generator i
constraints = [constraints, Pgmin(i) <= Pg(i)];
% Maximum active power output constraint for generator i
constraints = [constraints, Pg(i) <= Pgmax(i)];
% Minimum reactive power output constraint for generator i
constraints = [constraints, Qgmin(i) <= Qg(i)];
% Maximum reactive power output constraint for generator i
constraints = [constraints, Qg(i) <= Qgmax(i)];
end
% Bus voltage limit constraints
for i = 1:nb
% Minimum bus voltage magnitude constraint for bus i
constraints = [constraints, Vmin(i) <= V(i)];
% Maximum bus voltage magnitude constraint for bus i
constraints = [constraints, V(i) <= Vmax(i)];
end
% Branch power flow limit constraints
for i = 1:nl
% Calculate active power flow on branch i (assuming the "from" bus is the positive direction)
Pl(i) = V(fbus(i))^2 * Gbus(fbus(i), tbus(i)) – V(fbus(i)) * V(tbus(i)) * (Gbus(fbus(i), tbus(i)) * cos(theta(fbus(i) – theta(tbus(i))) + Bbus(fbus(i), tbus(i)) * sin(theta(fbus(i) – theta(tbus(i)))));
% Absolute value constraint for active power flow on branch i
constraints = [constraints, abs(Pl(i)) <= Plmax(i)];
end
% Solve the optimal power flow problem
result = solvesdp(constraints, objective); % Use YALMIP to solve the optimal power flow problem
% Output and analyze the results
if result.problem == 0 % If the solution is successful
disp(‘Optimal Power Flow Solved Successfully!’); % Display success message
disp(‘Total System Operating Cost:’); % Display total system operating cost
value(objective) % Display the objective function value
disp(‘Generator Active Power Output:’); % Display generator active power output
value(Pg) % Display the generator active power output variable values
disp(‘Generator Reactive Power Output:’); % Display generator reactive power output
value(Qg) % Display the generator reactive power output variable values
disp(‘Bus Voltage Magnitude:’); % Display bus voltage magnitude
value(V) % Display the bus voltage magnitude variable values
disp(‘Bus Voltage Angle (in degrees):’); % Display bus voltage angle (in degrees)
rad2deg(value(theta)) % Display bus voltage angle variable values and convert to degrees
disp(‘Branch Active Power Flow:’); % Display branch active power flow
value(Pl)
endI use MATLAB-YALMIP to write the optimal trend program based on the IEEEE14 system, but I can’t converge. Please help to see if the program is wrong?
code:
% Optimal Power Flow Example
% Based on the IEEE 14-bus standard case (i.e., case14 in Matpower)
% Implemented in MATLAB with YALMIP
clear; clc;
% Load power system data
mpc = loadcase(‘case14’); % You can also load other data files, such as case9, case30, etc.
% Define variables and parameters
nb = size(mpc.bus, 1); % Number of buses (nodes)
nl = size(mpc.branch, 1); % Number of branches (lines)
ng = size(mpc.gen, 1); % Number of generators
nr = nb – ng; % Number of load buses
% Extract node data
bus_id = mpc.bus(:, 1); % Bus IDs
bus_type = mpc.bus(:, 2); % Bus types (1-PQ, 2-PV, 3-Slack)
Pd = mpc.bus(:, 3); % Active power demand (MW)
Qd = mpc.bus(:, 4); % Reactive power demand (MVAr)
Vmin = mpc.bus(:, 13); % Minimum bus voltage (p.u.)
Vmax = mpc.bus(:, 12); % Maximum bus voltage (p.u.)
% Extract generator data
gen_id = mpc.gen(:, 1); % Bus IDs where generators are connected
Pgmin = mpc.gen(:, 10); % Minimum generator active power output (MW)
Pgmax = mpc.gen(:, 9); % Maximum generator active power output (MW)
Qgmin = mpc.gen(:, 5); % Minimum generator reactive power output (MVAr)
Qgmax = mpc.gen(:, 4); % Maximum generator reactive power output (MVAr)
a2 = mpc.gencost(:, 5); % Generator cost curve coefficient for quadratic term
a1 = mpc.gencost(:, 6); % Generator cost curve coefficient for linear term
a0 = mpc.gencost(:, 7); % Generator cost curve constant term
% Extract branch data
fbus = mpc.branch(:, 1); % "From" bus (starting node) of each branch
tbus = mpc.branch(:, 2); % "To" bus (ending node) of each branch
Plmax = ones(nl, 1) * 4000; % Maximum branch active power flow limit (MW)
% Plmax = mpc.branch(:, 6) .* mpc.branch(:, 3) * 1e-3; % Maximum branch active power flow limit (MW)
% Calculate the bus admittance matrix
[Ybus, ~, ~] = makeYbus(mpc); % Use a Matpower function to calculate the bus admittance matrix
Gbus = real(Ybus); % Real part of bus admittance matrix (conductance)
Bbus = imag(Ybus); % Imaginary part of bus admittance matrix (susceptance)
% Define YALMIP variables
Pg = sdpvar(ng, 1, ‘full’); % Generator active power output variables
Qg = sdpvar(ng, 1, ‘full’); % Generator reactive power output variables
V = sdpvar(nb, 1, ‘full’); % Bus voltage magnitude variables
theta = sdpvar(nb, 1, ‘full’); % Bus voltage angle variables
Pl = sdpvar(nl, 1, ‘full’); % Branch active power flow variables
% Define the objective function
objective = sum(a2 .* Pg.^2 + a1 .* Pg + a0); % Minimize the total operating cost
% Define constraints
constraints = [];
% Node power balance constraints
for i = 1:nb
% Active power balance equation for node i
if ismember(i, gen_id)
record = find(gen_id == i);
constraints = [constraints, Pg(record) – Pd(i) – V(i) * sum(V * (Gbus(i, 🙂 * cos(theta(i) – theta) + Bbus(i, 🙂 * sin(theta(i) – theta))) == 0];
constraints = [constraints, Qg(record) – Qd(i) + V(i) * sum(V * (Gbus(i, 🙂 * sin(theta(i) – theta) – Bbus(i, 🙂 * cos(theta(i) – theta))) == 0];
else
constraints = [constraints, -Pd(i) – V(i) * sum(V * (Gbus(i, 🙂 * cos(theta(i) – theta) + Bbus(i, 🙂 * sin(theta(i) – theta))) == 0];
constraints = [constraints, -Qd(i) + V(i) * sum(V * (Gbus(i, 🙂 * sin(theta(i) – theta) – Bbus(i, 🙂 * cos(theta(i) – theta))) == 0];
end
end
% Generator output limit constraints
for i = 1:ng
% Minimum active power output constraint for generator i
constraints = [constraints, Pgmin(i) <= Pg(i)];
% Maximum active power output constraint for generator i
constraints = [constraints, Pg(i) <= Pgmax(i)];
% Minimum reactive power output constraint for generator i
constraints = [constraints, Qgmin(i) <= Qg(i)];
% Maximum reactive power output constraint for generator i
constraints = [constraints, Qg(i) <= Qgmax(i)];
end
% Bus voltage limit constraints
for i = 1:nb
% Minimum bus voltage magnitude constraint for bus i
constraints = [constraints, Vmin(i) <= V(i)];
% Maximum bus voltage magnitude constraint for bus i
constraints = [constraints, V(i) <= Vmax(i)];
end
% Branch power flow limit constraints
for i = 1:nl
% Calculate active power flow on branch i (assuming the "from" bus is the positive direction)
Pl(i) = V(fbus(i))^2 * Gbus(fbus(i), tbus(i)) – V(fbus(i)) * V(tbus(i)) * (Gbus(fbus(i), tbus(i)) * cos(theta(fbus(i) – theta(tbus(i))) + Bbus(fbus(i), tbus(i)) * sin(theta(fbus(i) – theta(tbus(i)))));
% Absolute value constraint for active power flow on branch i
constraints = [constraints, abs(Pl(i)) <= Plmax(i)];
end
% Solve the optimal power flow problem
result = solvesdp(constraints, objective); % Use YALMIP to solve the optimal power flow problem
% Output and analyze the results
if result.problem == 0 % If the solution is successful
disp(‘Optimal Power Flow Solved Successfully!’); % Display success message
disp(‘Total System Operating Cost:’); % Display total system operating cost
value(objective) % Display the objective function value
disp(‘Generator Active Power Output:’); % Display generator active power output
value(Pg) % Display the generator active power output variable values
disp(‘Generator Reactive Power Output:’); % Display generator reactive power output
value(Qg) % Display the generator reactive power output variable values
disp(‘Bus Voltage Magnitude:’); % Display bus voltage magnitude
value(V) % Display the bus voltage magnitude variable values
disp(‘Bus Voltage Angle (in degrees):’); % Display bus voltage angle (in degrees)
rad2deg(value(theta)) % Display bus voltage angle variable values and convert to degrees
disp(‘Branch Active Power Flow:’); % Display branch active power flow
value(Pl)
end I use MATLAB-YALMIP to write the optimal trend program based on the IEEEE14 system, but I can’t converge. Please help to see if the program is wrong?
code:
% Optimal Power Flow Example
% Based on the IEEE 14-bus standard case (i.e., case14 in Matpower)
% Implemented in MATLAB with YALMIP
clear; clc;
% Load power system data
mpc = loadcase(‘case14’); % You can also load other data files, such as case9, case30, etc.
% Define variables and parameters
nb = size(mpc.bus, 1); % Number of buses (nodes)
nl = size(mpc.branch, 1); % Number of branches (lines)
ng = size(mpc.gen, 1); % Number of generators
nr = nb – ng; % Number of load buses
% Extract node data
bus_id = mpc.bus(:, 1); % Bus IDs
bus_type = mpc.bus(:, 2); % Bus types (1-PQ, 2-PV, 3-Slack)
Pd = mpc.bus(:, 3); % Active power demand (MW)
Qd = mpc.bus(:, 4); % Reactive power demand (MVAr)
Vmin = mpc.bus(:, 13); % Minimum bus voltage (p.u.)
Vmax = mpc.bus(:, 12); % Maximum bus voltage (p.u.)
% Extract generator data
gen_id = mpc.gen(:, 1); % Bus IDs where generators are connected
Pgmin = mpc.gen(:, 10); % Minimum generator active power output (MW)
Pgmax = mpc.gen(:, 9); % Maximum generator active power output (MW)
Qgmin = mpc.gen(:, 5); % Minimum generator reactive power output (MVAr)
Qgmax = mpc.gen(:, 4); % Maximum generator reactive power output (MVAr)
a2 = mpc.gencost(:, 5); % Generator cost curve coefficient for quadratic term
a1 = mpc.gencost(:, 6); % Generator cost curve coefficient for linear term
a0 = mpc.gencost(:, 7); % Generator cost curve constant term
% Extract branch data
fbus = mpc.branch(:, 1); % "From" bus (starting node) of each branch
tbus = mpc.branch(:, 2); % "To" bus (ending node) of each branch
Plmax = ones(nl, 1) * 4000; % Maximum branch active power flow limit (MW)
% Plmax = mpc.branch(:, 6) .* mpc.branch(:, 3) * 1e-3; % Maximum branch active power flow limit (MW)
% Calculate the bus admittance matrix
[Ybus, ~, ~] = makeYbus(mpc); % Use a Matpower function to calculate the bus admittance matrix
Gbus = real(Ybus); % Real part of bus admittance matrix (conductance)
Bbus = imag(Ybus); % Imaginary part of bus admittance matrix (susceptance)
% Define YALMIP variables
Pg = sdpvar(ng, 1, ‘full’); % Generator active power output variables
Qg = sdpvar(ng, 1, ‘full’); % Generator reactive power output variables
V = sdpvar(nb, 1, ‘full’); % Bus voltage magnitude variables
theta = sdpvar(nb, 1, ‘full’); % Bus voltage angle variables
Pl = sdpvar(nl, 1, ‘full’); % Branch active power flow variables
% Define the objective function
objective = sum(a2 .* Pg.^2 + a1 .* Pg + a0); % Minimize the total operating cost
% Define constraints
constraints = [];
% Node power balance constraints
for i = 1:nb
% Active power balance equation for node i
if ismember(i, gen_id)
record = find(gen_id == i);
constraints = [constraints, Pg(record) – Pd(i) – V(i) * sum(V * (Gbus(i, 🙂 * cos(theta(i) – theta) + Bbus(i, 🙂 * sin(theta(i) – theta))) == 0];
constraints = [constraints, Qg(record) – Qd(i) + V(i) * sum(V * (Gbus(i, 🙂 * sin(theta(i) – theta) – Bbus(i, 🙂 * cos(theta(i) – theta))) == 0];
else
constraints = [constraints, -Pd(i) – V(i) * sum(V * (Gbus(i, 🙂 * cos(theta(i) – theta) + Bbus(i, 🙂 * sin(theta(i) – theta))) == 0];
constraints = [constraints, -Qd(i) + V(i) * sum(V * (Gbus(i, 🙂 * sin(theta(i) – theta) – Bbus(i, 🙂 * cos(theta(i) – theta))) == 0];
end
end
% Generator output limit constraints
for i = 1:ng
% Minimum active power output constraint for generator i
constraints = [constraints, Pgmin(i) <= Pg(i)];
% Maximum active power output constraint for generator i
constraints = [constraints, Pg(i) <= Pgmax(i)];
% Minimum reactive power output constraint for generator i
constraints = [constraints, Qgmin(i) <= Qg(i)];
% Maximum reactive power output constraint for generator i
constraints = [constraints, Qg(i) <= Qgmax(i)];
end
% Bus voltage limit constraints
for i = 1:nb
% Minimum bus voltage magnitude constraint for bus i
constraints = [constraints, Vmin(i) <= V(i)];
% Maximum bus voltage magnitude constraint for bus i
constraints = [constraints, V(i) <= Vmax(i)];
end
% Branch power flow limit constraints
for i = 1:nl
% Calculate active power flow on branch i (assuming the "from" bus is the positive direction)
Pl(i) = V(fbus(i))^2 * Gbus(fbus(i), tbus(i)) – V(fbus(i)) * V(tbus(i)) * (Gbus(fbus(i), tbus(i)) * cos(theta(fbus(i) – theta(tbus(i))) + Bbus(fbus(i), tbus(i)) * sin(theta(fbus(i) – theta(tbus(i)))));
% Absolute value constraint for active power flow on branch i
constraints = [constraints, abs(Pl(i)) <= Plmax(i)];
end
% Solve the optimal power flow problem
result = solvesdp(constraints, objective); % Use YALMIP to solve the optimal power flow problem
% Output and analyze the results
if result.problem == 0 % If the solution is successful
disp(‘Optimal Power Flow Solved Successfully!’); % Display success message
disp(‘Total System Operating Cost:’); % Display total system operating cost
value(objective) % Display the objective function value
disp(‘Generator Active Power Output:’); % Display generator active power output
value(Pg) % Display the generator active power output variable values
disp(‘Generator Reactive Power Output:’); % Display generator reactive power output
value(Qg) % Display the generator reactive power output variable values
disp(‘Bus Voltage Magnitude:’); % Display bus voltage magnitude
value(V) % Display the bus voltage magnitude variable values
disp(‘Bus Voltage Angle (in degrees):’); % Display bus voltage angle (in degrees)
rad2deg(value(theta)) % Display bus voltage angle variable values and convert to degrees
disp(‘Branch Active Power Flow:’); % Display branch active power flow
value(Pl)
end yalmip, opf, matlab, optimal power flow MATLAB Answers — New Questions
‘mcc’ ignoring “-w disable” option
I’m using a Makefile (on Linux) to call ‘mcc’ (R2017b) to compile multiple projects. I’ve added the "-w disable" option, and when ‘make’ prints out the command line, the option is there. But the console output still contains warning messages. Am I missing or not correctly understanding something?
In case it’s important, the specific warning I really want to suppress is MATLAB:depfun:req:CorrespondingMCodeIsEmpty. There are 1000s of lines of console output for this warning type, but I know everything compiles and works fine. So I want to improve my odds of catching any other warnings that might show up. Trying to disable just that one warning wasn’t working, so I tried to disable all warnings and discovered this problem.
Again, in case it’s important, these warnings are being triggered by P-code files that are being brought in via a "-a" specification.
The full command line being issued by ‘make’ is like:
cd mcc/linux && /path/to/mcc -R -nodesktop -m -v -w disable -a /path/to/pcode -a /another/path/to/pcode /path/to/source.p
All assistance appreciated!I’m using a Makefile (on Linux) to call ‘mcc’ (R2017b) to compile multiple projects. I’ve added the "-w disable" option, and when ‘make’ prints out the command line, the option is there. But the console output still contains warning messages. Am I missing or not correctly understanding something?
In case it’s important, the specific warning I really want to suppress is MATLAB:depfun:req:CorrespondingMCodeIsEmpty. There are 1000s of lines of console output for this warning type, but I know everything compiles and works fine. So I want to improve my odds of catching any other warnings that might show up. Trying to disable just that one warning wasn’t working, so I tried to disable all warnings and discovered this problem.
Again, in case it’s important, these warnings are being triggered by P-code files that are being brought in via a "-a" specification.
The full command line being issued by ‘make’ is like:
cd mcc/linux && /path/to/mcc -R -nodesktop -m -v -w disable -a /path/to/pcode -a /another/path/to/pcode /path/to/source.p
All assistance appreciated! I’m using a Makefile (on Linux) to call ‘mcc’ (R2017b) to compile multiple projects. I’ve added the "-w disable" option, and when ‘make’ prints out the command line, the option is there. But the console output still contains warning messages. Am I missing or not correctly understanding something?
In case it’s important, the specific warning I really want to suppress is MATLAB:depfun:req:CorrespondingMCodeIsEmpty. There are 1000s of lines of console output for this warning type, but I know everything compiles and works fine. So I want to improve my odds of catching any other warnings that might show up. Trying to disable just that one warning wasn’t working, so I tried to disable all warnings and discovered this problem.
Again, in case it’s important, these warnings are being triggered by P-code files that are being brought in via a "-a" specification.
The full command line being issued by ‘make’ is like:
cd mcc/linux && /path/to/mcc -R -nodesktop -m -v -w disable -a /path/to/pcode -a /another/path/to/pcode /path/to/source.p
All assistance appreciated! matlab compiler, linux, mcc, makefile, disable warnings MATLAB Answers — New Questions
Is there a way to use the Vehicle 6DOF block with steering angle and wheel speed as inputs?
The 3 DOF Vehicle Body Block supports steering angle and wheel speed as inputs, but the 6 DOF Vehicle Body Block only seems to support suspension and external forces and moments as inputs.
Is there a way to use the 6 DOF block with steering angle and wheel speed control inputs, and perhaps an additional environment input? I know the Constant Radius Reference Application uses the 6DOF block under the hood, but this is a huge step up in complexity from the 2-dimensional 3DOF block. Looking to make the jump from 2-D to 3-D, but preferably still using typical control inputs.The 3 DOF Vehicle Body Block supports steering angle and wheel speed as inputs, but the 6 DOF Vehicle Body Block only seems to support suspension and external forces and moments as inputs.
Is there a way to use the 6 DOF block with steering angle and wheel speed control inputs, and perhaps an additional environment input? I know the Constant Radius Reference Application uses the 6DOF block under the hood, but this is a huge step up in complexity from the 2-dimensional 3DOF block. Looking to make the jump from 2-D to 3-D, but preferably still using typical control inputs. The 3 DOF Vehicle Body Block supports steering angle and wheel speed as inputs, but the 6 DOF Vehicle Body Block only seems to support suspension and external forces and moments as inputs.
Is there a way to use the 6 DOF block with steering angle and wheel speed control inputs, and perhaps an additional environment input? I know the Constant Radius Reference Application uses the 6DOF block under the hood, but this is a huge step up in complexity from the 2-dimensional 3DOF block. Looking to make the jump from 2-D to 3-D, but preferably still using typical control inputs. vehicle dynamics, 6dof, simulink MATLAB Answers — New Questions
A few basic Simulink/Simscape questions
In the past I’ve generally used Simulink simulations for short bursts of transient analysis.
I was curious if it were possible to use it more like LabView, where a simulation can also run forever (tstop = inf), and you can interact with and modify the setup in run time by pushing buttons (opening and closing SimScape circuits).
Regarding memory, I would not want to store all time data. It would be good to store the trailing 10000 points. I’m not sure how to do that either.In the past I’ve generally used Simulink simulations for short bursts of transient analysis.
I was curious if it were possible to use it more like LabView, where a simulation can also run forever (tstop = inf), and you can interact with and modify the setup in run time by pushing buttons (opening and closing SimScape circuits).
Regarding memory, I would not want to store all time data. It would be good to store the trailing 10000 points. I’m not sure how to do that either. In the past I’ve generally used Simulink simulations for short bursts of transient analysis.
I was curious if it were possible to use it more like LabView, where a simulation can also run forever (tstop = inf), and you can interact with and modify the setup in run time by pushing buttons (opening and closing SimScape circuits).
Regarding memory, I would not want to store all time data. It would be good to store the trailing 10000 points. I’m not sure how to do that either. simulink, simscape, interactive buttons, memory MATLAB Answers — New Questions
PCQI code doesn’t showing any output neither any error
I need to take output from a "PCQI: A Patch-Structure Representation Method for Quality Assessment of Contrast Changed Images" code. But whenever i run this, it doesnt show anything at all. Not even an error. How can i solve this?
Demo.m
clc;
clear;
im1=imread(‘ref.png’);
im2=imread(‘contrast_changed.png’);
im1=double(rgb2gray(im1));
im2=double(rgb2gray(im2));
[mpcqi, pcqi_map] = PCQI(im1, im2);
PCQI.m (default value for window = fspecial(‘gaussian’, 11, 1.5); L = 256)
function [mpcqi, pcqi_map]= PCQI(img1, img2, window, L)
if (nargin < 2 || nargin > 4)
mpcqi = -Inf;
pcqi_map = -Inf;
return;
end
if (size(img1) ~= size(img2))
mpcqi = -Inf;
pcqi_map = -Inf;
return;
end
[M N] = size(img1);
if (nargin == 2)
if ((M < 11) || (N < 11))
mpcqi = -Inf;
pcqi_map = -Inf;
return
end
window = fspecial(‘gaussian’, 11, 1.5);
L = 256;
end
if (nargin == 3)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
mpcqi = -Inf;
pcqi_map = -Inf;
return
end
L = 255;
end
if (nargin == 4)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
mpcqi = -Inf;
pcqi_map = -Inf;
return
end
end
window = window/sum(sum(window));
mu1 = filter2(window, img1, ‘valid’);
mu2 = filter2(window, img2, ‘valid’);
mu1_sq = mu1.*mu1;
mu2_sq = mu2.*mu2;
mu1_mu2 = mu1.*mu2;
sigma1_sq = filter2(window, img1.*img1, ‘valid’) – mu1_sq;
sigma2_sq = filter2(window, img2.*img2, ‘valid’) – mu2_sq;
sigma12 = filter2(window, img1.*img2, ‘valid’) – mu1_mu2;
sigma1_sq = max(0, sigma1_sq);
sigma2_sq = max(0, sigma2_sq);
C=3;
pcqi_map = (4/pi) *atan((sigma12 + C )./(sigma1_sq + C ));
pcqi_map = pcqi_map .*((sigma12 + C) ./(sqrt(sigma1_sq).*sqrt(sigma2_sq) + C));
pcqi_map = pcqi_map .*exp(-abs(mu1-mu2)/L);
mpcqi = mean2(pcqi_map);
returnI need to take output from a "PCQI: A Patch-Structure Representation Method for Quality Assessment of Contrast Changed Images" code. But whenever i run this, it doesnt show anything at all. Not even an error. How can i solve this?
Demo.m
clc;
clear;
im1=imread(‘ref.png’);
im2=imread(‘contrast_changed.png’);
im1=double(rgb2gray(im1));
im2=double(rgb2gray(im2));
[mpcqi, pcqi_map] = PCQI(im1, im2);
PCQI.m (default value for window = fspecial(‘gaussian’, 11, 1.5); L = 256)
function [mpcqi, pcqi_map]= PCQI(img1, img2, window, L)
if (nargin < 2 || nargin > 4)
mpcqi = -Inf;
pcqi_map = -Inf;
return;
end
if (size(img1) ~= size(img2))
mpcqi = -Inf;
pcqi_map = -Inf;
return;
end
[M N] = size(img1);
if (nargin == 2)
if ((M < 11) || (N < 11))
mpcqi = -Inf;
pcqi_map = -Inf;
return
end
window = fspecial(‘gaussian’, 11, 1.5);
L = 256;
end
if (nargin == 3)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
mpcqi = -Inf;
pcqi_map = -Inf;
return
end
L = 255;
end
if (nargin == 4)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
mpcqi = -Inf;
pcqi_map = -Inf;
return
end
end
window = window/sum(sum(window));
mu1 = filter2(window, img1, ‘valid’);
mu2 = filter2(window, img2, ‘valid’);
mu1_sq = mu1.*mu1;
mu2_sq = mu2.*mu2;
mu1_mu2 = mu1.*mu2;
sigma1_sq = filter2(window, img1.*img1, ‘valid’) – mu1_sq;
sigma2_sq = filter2(window, img2.*img2, ‘valid’) – mu2_sq;
sigma12 = filter2(window, img1.*img2, ‘valid’) – mu1_mu2;
sigma1_sq = max(0, sigma1_sq);
sigma2_sq = max(0, sigma2_sq);
C=3;
pcqi_map = (4/pi) *atan((sigma12 + C )./(sigma1_sq + C ));
pcqi_map = pcqi_map .*((sigma12 + C) ./(sqrt(sigma1_sq).*sqrt(sigma2_sq) + C));
pcqi_map = pcqi_map .*exp(-abs(mu1-mu2)/L);
mpcqi = mean2(pcqi_map);
return I need to take output from a "PCQI: A Patch-Structure Representation Method for Quality Assessment of Contrast Changed Images" code. But whenever i run this, it doesnt show anything at all. Not even an error. How can i solve this?
Demo.m
clc;
clear;
im1=imread(‘ref.png’);
im2=imread(‘contrast_changed.png’);
im1=double(rgb2gray(im1));
im2=double(rgb2gray(im2));
[mpcqi, pcqi_map] = PCQI(im1, im2);
PCQI.m (default value for window = fspecial(‘gaussian’, 11, 1.5); L = 256)
function [mpcqi, pcqi_map]= PCQI(img1, img2, window, L)
if (nargin < 2 || nargin > 4)
mpcqi = -Inf;
pcqi_map = -Inf;
return;
end
if (size(img1) ~= size(img2))
mpcqi = -Inf;
pcqi_map = -Inf;
return;
end
[M N] = size(img1);
if (nargin == 2)
if ((M < 11) || (N < 11))
mpcqi = -Inf;
pcqi_map = -Inf;
return
end
window = fspecial(‘gaussian’, 11, 1.5);
L = 256;
end
if (nargin == 3)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
mpcqi = -Inf;
pcqi_map = -Inf;
return
end
L = 255;
end
if (nargin == 4)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
mpcqi = -Inf;
pcqi_map = -Inf;
return
end
end
window = window/sum(sum(window));
mu1 = filter2(window, img1, ‘valid’);
mu2 = filter2(window, img2, ‘valid’);
mu1_sq = mu1.*mu1;
mu2_sq = mu2.*mu2;
mu1_mu2 = mu1.*mu2;
sigma1_sq = filter2(window, img1.*img1, ‘valid’) – mu1_sq;
sigma2_sq = filter2(window, img2.*img2, ‘valid’) – mu2_sq;
sigma12 = filter2(window, img1.*img2, ‘valid’) – mu1_mu2;
sigma1_sq = max(0, sigma1_sq);
sigma2_sq = max(0, sigma2_sq);
C=3;
pcqi_map = (4/pi) *atan((sigma12 + C )./(sigma1_sq + C ));
pcqi_map = pcqi_map .*((sigma12 + C) ./(sqrt(sigma1_sq).*sqrt(sigma2_sq) + C));
pcqi_map = pcqi_map .*exp(-abs(mu1-mu2)/L);
mpcqi = mean2(pcqi_map);
return image analysis, pcqi MATLAB Answers — New Questions
Simulink Project Change Resource Folder Location
Currently, I have a 2020a Simulink project where the resource folder is located in "resources". My group is trying to change that "resources" folder to ".SimulinkProject" but we cannot find where to do that. The Matlab preferences has the location as the preferred one already.
Is there a way to migrate that location?Currently, I have a 2020a Simulink project where the resource folder is located in "resources". My group is trying to change that "resources" folder to ".SimulinkProject" but we cannot find where to do that. The Matlab preferences has the location as the preferred one already.
Is there a way to migrate that location? Currently, I have a 2020a Simulink project where the resource folder is located in "resources". My group is trying to change that "resources" folder to ".SimulinkProject" but we cannot find where to do that. The Matlab preferences has the location as the preferred one already.
Is there a way to migrate that location? simulink, project MATLAB Answers — New Questions
Best way to retrieve items from a cell array using a cell array of indices?
Hi I am porting a script I had in Python to Matlab. Also returning to MATLAB after a decade, so pardon me if it’s too basic.
The key issue I am having is, retrieving premapped items from a cell array. Example, I have:
label_names={"assds", "Sasas", "Asasa", "assds"}
indices={[1 3 2]} %note that this can have varying lengths from 1 to full length of the label array.
label_names(indices) %of course returns an error
Error is "Unable to use a value of type cell as an index."
What is the best way to achieve this – retreive items based on a cell array of indices – as cleanly as possible?
PS: The reason they are cell arrays has to do with varying lengths. To avoid X-Y problem, lets assume rest of the code is done optimally.
Thanks!Hi I am porting a script I had in Python to Matlab. Also returning to MATLAB after a decade, so pardon me if it’s too basic.
The key issue I am having is, retrieving premapped items from a cell array. Example, I have:
label_names={"assds", "Sasas", "Asasa", "assds"}
indices={[1 3 2]} %note that this can have varying lengths from 1 to full length of the label array.
label_names(indices) %of course returns an error
Error is "Unable to use a value of type cell as an index."
What is the best way to achieve this – retreive items based on a cell array of indices – as cleanly as possible?
PS: The reason they are cell arrays has to do with varying lengths. To avoid X-Y problem, lets assume rest of the code is done optimally.
Thanks! Hi I am porting a script I had in Python to Matlab. Also returning to MATLAB after a decade, so pardon me if it’s too basic.
The key issue I am having is, retrieving premapped items from a cell array. Example, I have:
label_names={"assds", "Sasas", "Asasa", "assds"}
indices={[1 3 2]} %note that this can have varying lengths from 1 to full length of the label array.
label_names(indices) %of course returns an error
Error is "Unable to use a value of type cell as an index."
What is the best way to achieve this – retreive items based on a cell array of indices – as cleanly as possible?
PS: The reason they are cell arrays has to do with varying lengths. To avoid X-Y problem, lets assume rest of the code is done optimally.
Thanks! cell array, indexing MATLAB Answers — New Questions
Stereo camera calibration app not see images in folder to upload while camera calibration app can still see
Hello there,
Stereo camera calibration app not see images in folder to upload while camera calibration app can still see
I tried both jpg & png images
Sincerely yours,
Truong MaiHello there,
Stereo camera calibration app not see images in folder to upload while camera calibration app can still see
I tried both jpg & png images
Sincerely yours,
Truong Mai Hello there,
Stereo camera calibration app not see images in folder to upload while camera calibration app can still see
I tried both jpg & png images
Sincerely yours,
Truong Mai stereo camera calibration MATLAB Answers — New Questions
Finding a circle in a 2D array
This is not circle finding in an image, which has been well covered, but in an array.
I have an array P with several approximately-circular areas of a low value. I would like to find the centres of those areas to calibrate my device. Here is a contour 2D plot of P. The contour plot looks a bit odd because I only obtained a patch of data around each circle (the box) and it is doing a linear interpolation between those.
This is a one-time calibration so I’m happy to do some manual setting up work.
Thanks in advance!
Jack
This is how I display the contour:
figure(1)
pcolor(X,Y,P);
shading interp
hold on
colorbar
hold off
PS this is my first question so do say if there is anything I can improve for next time.This is not circle finding in an image, which has been well covered, but in an array.
I have an array P with several approximately-circular areas of a low value. I would like to find the centres of those areas to calibrate my device. Here is a contour 2D plot of P. The contour plot looks a bit odd because I only obtained a patch of data around each circle (the box) and it is doing a linear interpolation between those.
This is a one-time calibration so I’m happy to do some manual setting up work.
Thanks in advance!
Jack
This is how I display the contour:
figure(1)
pcolor(X,Y,P);
shading interp
hold on
colorbar
hold off
PS this is my first question so do say if there is anything I can improve for next time. This is not circle finding in an image, which has been well covered, but in an array.
I have an array P with several approximately-circular areas of a low value. I would like to find the centres of those areas to calibrate my device. Here is a contour 2D plot of P. The contour plot looks a bit odd because I only obtained a patch of data around each circle (the box) and it is doing a linear interpolation between those.
This is a one-time calibration so I’m happy to do some manual setting up work.
Thanks in advance!
Jack
This is how I display the contour:
figure(1)
pcolor(X,Y,P);
shading interp
hold on
colorbar
hold off
PS this is my first question so do say if there is anything I can improve for next time. circles, finding, arrays, variables, matlab MATLAB Answers — New Questions
Simulink random number generation same seed in model and code generation
The Simulink Random Number block allows seeding with a positive integer (as a double type). When generating C code the seed is converted to a uint32 but it is not obvious how.
I can call the generated code and set a seed (as a uint32), how could i set the same seed in the Simulink Model? I need to run from the same seed in both Simulink and C, being able to set each at the start of a run (rather than regenerate C with new seed)The Simulink Random Number block allows seeding with a positive integer (as a double type). When generating C code the seed is converted to a uint32 but it is not obvious how.
I can call the generated code and set a seed (as a uint32), how could i set the same seed in the Simulink Model? I need to run from the same seed in both Simulink and C, being able to set each at the start of a run (rather than regenerate C with new seed) The Simulink Random Number block allows seeding with a positive integer (as a double type). When generating C code the seed is converted to a uint32 but it is not obvious how.
I can call the generated code and set a seed (as a uint32), how could i set the same seed in the Simulink Model? I need to run from the same seed in both Simulink and C, being able to set each at the start of a run (rather than regenerate C with new seed) simulink, random number generator MATLAB Answers — New Questions
Capturing Lossless Images with Image Acquisition Toolbox (getsnasphot)
Hello everyone,
This is a follow-up to an earlier question I had asked about capturing lossless images with Matlab. Earlier, I was using USB Webcam Package’s snapshot() function to capture, yet it seemed that there was some compression going on possibly because it was not possible to access YUY2 (I am not sure if this is relevant as I want to capture images rather than recording videos). Now I have moved on to use the Image Acquisition Toolbox and the interface generated the following code to capture images:
v = videoinput("winvideo", 1, "YUY2_3840x2160"); % Video device
v.ReturnedColorspace = "RGB";
src = getselectedsource(v);
src.Exposure = 0; % Camera parameters
image1 = getsnapshot(v); % Capturing the image
filename = "snapshot1.bmp"; % I changed the code to save the image as .bmp
imwrite(image1, filename, "bmp"); % Saving the file
Now the code is using the getsnapshot() function instead. Should this apply any additional compression on Matlab’s side of things? I know that the camera may do something but I want to ensure that Matlab does not.Hello everyone,
This is a follow-up to an earlier question I had asked about capturing lossless images with Matlab. Earlier, I was using USB Webcam Package’s snapshot() function to capture, yet it seemed that there was some compression going on possibly because it was not possible to access YUY2 (I am not sure if this is relevant as I want to capture images rather than recording videos). Now I have moved on to use the Image Acquisition Toolbox and the interface generated the following code to capture images:
v = videoinput("winvideo", 1, "YUY2_3840x2160"); % Video device
v.ReturnedColorspace = "RGB";
src = getselectedsource(v);
src.Exposure = 0; % Camera parameters
image1 = getsnapshot(v); % Capturing the image
filename = "snapshot1.bmp"; % I changed the code to save the image as .bmp
imwrite(image1, filename, "bmp"); % Saving the file
Now the code is using the getsnapshot() function instead. Should this apply any additional compression on Matlab’s side of things? I know that the camera may do something but I want to ensure that Matlab does not. Hello everyone,
This is a follow-up to an earlier question I had asked about capturing lossless images with Matlab. Earlier, I was using USB Webcam Package’s snapshot() function to capture, yet it seemed that there was some compression going on possibly because it was not possible to access YUY2 (I am not sure if this is relevant as I want to capture images rather than recording videos). Now I have moved on to use the Image Acquisition Toolbox and the interface generated the following code to capture images:
v = videoinput("winvideo", 1, "YUY2_3840x2160"); % Video device
v.ReturnedColorspace = "RGB";
src = getselectedsource(v);
src.Exposure = 0; % Camera parameters
image1 = getsnapshot(v); % Capturing the image
filename = "snapshot1.bmp"; % I changed the code to save the image as .bmp
imwrite(image1, filename, "bmp"); % Saving the file
Now the code is using the getsnapshot() function instead. Should this apply any additional compression on Matlab’s side of things? I know that the camera may do something but I want to ensure that Matlab does not. image acquisition, lossless image, bitmap, camera, recording, video, image MATLAB Answers — New Questions
reference model building error in simulink realtime using speedgoat library 2024b
I have reference 3 model inside main model while build the main model in simulink realtime i am getting this error, these models are compiling/building individually.
Error : ### Checking status of model reference code generation target for model ‘abcd’ used in ‘MasterSpeedgoatModel’.
### Model reference code generation target (abcd.cpp) for model SwDev_IO_V2 was out of date. Binary information cache did not exist. slprj folder containing binary information cache might have been removed.
### Starting build procedure for: abcd ### Generating code and artifacts to ‘Model specific’ folder structure
Model reference code generation targets:
Model Build Reason Status Build Duration
=======================================================================================================================================
abcd Information cache folder or artifacts were missing. Failed to build. For more information, see build log. 0d
Top model targets:
Model Build Reason Status Build Duration
================================================================================================================================================
MainModel Information cache folder or artifacts were missing. Failed to build. For more information, see build log. 0d
0 of 4 models built (1 models already up to date)
Error:Error(s) encountered while building "abcd_rtwlib"I have reference 3 model inside main model while build the main model in simulink realtime i am getting this error, these models are compiling/building individually.
Error : ### Checking status of model reference code generation target for model ‘abcd’ used in ‘MasterSpeedgoatModel’.
### Model reference code generation target (abcd.cpp) for model SwDev_IO_V2 was out of date. Binary information cache did not exist. slprj folder containing binary information cache might have been removed.
### Starting build procedure for: abcd ### Generating code and artifacts to ‘Model specific’ folder structure
Model reference code generation targets:
Model Build Reason Status Build Duration
=======================================================================================================================================
abcd Information cache folder or artifacts were missing. Failed to build. For more information, see build log. 0d
Top model targets:
Model Build Reason Status Build Duration
================================================================================================================================================
MainModel Information cache folder or artifacts were missing. Failed to build. For more information, see build log. 0d
0 of 4 models built (1 models already up to date)
Error:Error(s) encountered while building "abcd_rtwlib" I have reference 3 model inside main model while build the main model in simulink realtime i am getting this error, these models are compiling/building individually.
Error : ### Checking status of model reference code generation target for model ‘abcd’ used in ‘MasterSpeedgoatModel’.
### Model reference code generation target (abcd.cpp) for model SwDev_IO_V2 was out of date. Binary information cache did not exist. slprj folder containing binary information cache might have been removed.
### Starting build procedure for: abcd ### Generating code and artifacts to ‘Model specific’ folder structure
Model reference code generation targets:
Model Build Reason Status Build Duration
=======================================================================================================================================
abcd Information cache folder or artifacts were missing. Failed to build. For more information, see build log. 0d
Top model targets:
Model Build Reason Status Build Duration
================================================================================================================================================
MainModel Information cache folder or artifacts were missing. Failed to build. For more information, see build log. 0d
0 of 4 models built (1 models already up to date)
Error:Error(s) encountered while building "abcd_rtwlib" simulink real time, speedgoat, library, io142, simulink, matlab 2024b MATLAB Answers — New Questions
array indices must be positive integers or logical values when complier matlab file – Application complier
Hi,
I have developed a function to be converted into exe file, the function include optimizer fmincon. The function is working well from matlab but when I converted into exe file using Application complier and start to run the exe file, the optimizer fmincon have this error "array indices must be positive integers or logical values".
Not sure what is wrong. Any help.Hi,
I have developed a function to be converted into exe file, the function include optimizer fmincon. The function is working well from matlab but when I converted into exe file using Application complier and start to run the exe file, the optimizer fmincon have this error "array indices must be positive integers or logical values".
Not sure what is wrong. Any help. Hi,
I have developed a function to be converted into exe file, the function include optimizer fmincon. The function is working well from matlab but when I converted into exe file using Application complier and start to run the exe file, the optimizer fmincon have this error "array indices must be positive integers or logical values".
Not sure what is wrong. Any help. application complier, fmincon, array indices must be positive integers or logical MATLAB Answers — New Questions
How to Call “convenc” DLL Compiled with MATLAB Library Compiler in VS2019?
Has anyone experienced compiling the MATLAB built-in function "convenc" into a DLL using the MATLAB Library Compiler and then calling it in VS2019 for development? If you have any related experience or steps to share, I would greatly appreciate it!Has anyone experienced compiling the MATLAB built-in function "convenc" into a DLL using the MATLAB Library Compiler and then calling it in VS2019 for development? If you have any related experience or steps to share, I would greatly appreciate it! Has anyone experienced compiling the MATLAB built-in function "convenc" into a DLL using the MATLAB Library Compiler and then calling it in VS2019 for development? If you have any related experience or steps to share, I would greatly appreciate it! convenc, library compiler MATLAB Answers — New Questions
nested loops to find values then execute commands
I have written a script to find the maximum and minimum values of 4 time series and then truncate each time series to these values as they are all of different length.
I want it to record the maximum and minimum values of all the time series first (lines 15-19), then after that store the overall smallest and largest values to new variables (lines 20-23).
At the moment, its constantly updating variables as it loops through, so its not using the overall smallest/largest values to truncate the time series.
I have tried putting lines 15-19 in another loop so it executes this first, but it doesnt seem to make any difference. Can anybody help?
%import all the csv files in the folder
csvFiles = dir(fullfile(folderPath, ‘*.csv’));
%read in all the csv files
for i = 1:length(csvFiles)
%get the individual file pathway
csvFilePath = fullfile(folderPath, csvFiles(i).name);
%read the file in
data = readmatrix(csvFilePath);
%remove nan’s from the timeseries
data = data(~any(isnan(data), 2), :);
%remove non-unique datapoints from the timeseries
[~, id] = unique(data(:,1)) ;
data = data(id,:);
for a = 1:length(csvFiles)
%find and save the maximum value of all the time series
maxVal(1) = max(data(:,1));
%find and save the minimum value of all the time series
minVal(1) = min(data(:,1));
%find and save the mean dt of all the time series
dt(1) = mean(diff(data(:,1)));
end
%find the time series that ends soonest
smallestMaxValue = min(maxVal)
%find the time series that starts latest
largestMinValue = max(minVal)
%truncate all the time series to the shortest one
truncateRow = find(data(:,1) > smallestMaxValue, 1, ‘first’); %find the index of the first value in the first column when the shortest time series is exceeded
if ~isempty(truncateRow)
truncatedData = data(1:truncateRow-1, :); %if there is a value in truncateRow, then truncate the dataset up to this point
else
truncatedData = data; %if there is no value in truncateRow (e.g. shortest time series), then leave the data as it is
end
endI have written a script to find the maximum and minimum values of 4 time series and then truncate each time series to these values as they are all of different length.
I want it to record the maximum and minimum values of all the time series first (lines 15-19), then after that store the overall smallest and largest values to new variables (lines 20-23).
At the moment, its constantly updating variables as it loops through, so its not using the overall smallest/largest values to truncate the time series.
I have tried putting lines 15-19 in another loop so it executes this first, but it doesnt seem to make any difference. Can anybody help?
%import all the csv files in the folder
csvFiles = dir(fullfile(folderPath, ‘*.csv’));
%read in all the csv files
for i = 1:length(csvFiles)
%get the individual file pathway
csvFilePath = fullfile(folderPath, csvFiles(i).name);
%read the file in
data = readmatrix(csvFilePath);
%remove nan’s from the timeseries
data = data(~any(isnan(data), 2), :);
%remove non-unique datapoints from the timeseries
[~, id] = unique(data(:,1)) ;
data = data(id,:);
for a = 1:length(csvFiles)
%find and save the maximum value of all the time series
maxVal(1) = max(data(:,1));
%find and save the minimum value of all the time series
minVal(1) = min(data(:,1));
%find and save the mean dt of all the time series
dt(1) = mean(diff(data(:,1)));
end
%find the time series that ends soonest
smallestMaxValue = min(maxVal)
%find the time series that starts latest
largestMinValue = max(minVal)
%truncate all the time series to the shortest one
truncateRow = find(data(:,1) > smallestMaxValue, 1, ‘first’); %find the index of the first value in the first column when the shortest time series is exceeded
if ~isempty(truncateRow)
truncatedData = data(1:truncateRow-1, :); %if there is a value in truncateRow, then truncate the dataset up to this point
else
truncatedData = data; %if there is no value in truncateRow (e.g. shortest time series), then leave the data as it is
end
end I have written a script to find the maximum and minimum values of 4 time series and then truncate each time series to these values as they are all of different length.
I want it to record the maximum and minimum values of all the time series first (lines 15-19), then after that store the overall smallest and largest values to new variables (lines 20-23).
At the moment, its constantly updating variables as it loops through, so its not using the overall smallest/largest values to truncate the time series.
I have tried putting lines 15-19 in another loop so it executes this first, but it doesnt seem to make any difference. Can anybody help?
%import all the csv files in the folder
csvFiles = dir(fullfile(folderPath, ‘*.csv’));
%read in all the csv files
for i = 1:length(csvFiles)
%get the individual file pathway
csvFilePath = fullfile(folderPath, csvFiles(i).name);
%read the file in
data = readmatrix(csvFilePath);
%remove nan’s from the timeseries
data = data(~any(isnan(data), 2), :);
%remove non-unique datapoints from the timeseries
[~, id] = unique(data(:,1)) ;
data = data(id,:);
for a = 1:length(csvFiles)
%find and save the maximum value of all the time series
maxVal(1) = max(data(:,1));
%find and save the minimum value of all the time series
minVal(1) = min(data(:,1));
%find and save the mean dt of all the time series
dt(1) = mean(diff(data(:,1)));
end
%find the time series that ends soonest
smallestMaxValue = min(maxVal)
%find the time series that starts latest
largestMinValue = max(minVal)
%truncate all the time series to the shortest one
truncateRow = find(data(:,1) > smallestMaxValue, 1, ‘first’); %find the index of the first value in the first column when the shortest time series is exceeded
if ~isempty(truncateRow)
truncatedData = data(1:truncateRow-1, :); %if there is a value in truncateRow, then truncate the dataset up to this point
else
truncatedData = data; %if there is no value in truncateRow (e.g. shortest time series), then leave the data as it is
end
end for loop, loop, nested loop MATLAB Answers — New Questions
How to classify using PCA (“pcares” function)
Hello.
I want to do a video classification.
I found some function about PCA.
https://www.mathworks.com/help/stats/pcares.html
[residuals,reconstructed] = pcares(X,5)
After using pcares(X,5), Can I classify data using "reconstructed"?
I mean, "reconstructed" is 3600 x 25.
1. After flattening each data, I got 90000 X 1.
2. I have 90 data, so I got 90 X 90001 (the last column is class).
3. Using classification methods like SVM, KNN, etc.
4. calculate the accuracy of the classification.
Is it a reasonable approach? or do I need to use other methods as PCA not "pcares".
When I use "reconstructed" data after "pcares", the accuracy of classification is so low.
Please let me know how to deal with this issue.Hello.
I want to do a video classification.
I found some function about PCA.
https://www.mathworks.com/help/stats/pcares.html
[residuals,reconstructed] = pcares(X,5)
After using pcares(X,5), Can I classify data using "reconstructed"?
I mean, "reconstructed" is 3600 x 25.
1. After flattening each data, I got 90000 X 1.
2. I have 90 data, so I got 90 X 90001 (the last column is class).
3. Using classification methods like SVM, KNN, etc.
4. calculate the accuracy of the classification.
Is it a reasonable approach? or do I need to use other methods as PCA not "pcares".
When I use "reconstructed" data after "pcares", the accuracy of classification is so low.
Please let me know how to deal with this issue. Hello.
I want to do a video classification.
I found some function about PCA.
https://www.mathworks.com/help/stats/pcares.html
[residuals,reconstructed] = pcares(X,5)
After using pcares(X,5), Can I classify data using "reconstructed"?
I mean, "reconstructed" is 3600 x 25.
1. After flattening each data, I got 90000 X 1.
2. I have 90 data, so I got 90 X 90001 (the last column is class).
3. Using classification methods like SVM, KNN, etc.
4. calculate the accuracy of the classification.
Is it a reasonable approach? or do I need to use other methods as PCA not "pcares".
When I use "reconstructed" data after "pcares", the accuracy of classification is so low.
Please let me know how to deal with this issue. classification, class, pca, dimensionality reduction, image analysis MATLAB Answers — New Questions
Why does Matlab crash when I try to access .NET 6.0 (core)?
Note: Workaround is to remove .NET 9.0 from PC to resolve conflicts with 6.0.
This might be a .NET issue as a whole, but I only see it using Matlab, so I am posting here to help others out facing the same issues.
I have a .dll from one of the groups I work with for communicating to our devices. The .dll was built in .NET 6.0 (core) (x64). I have been able to use it in the past in Matlab, but have now run into issues since installing Visual Studio 2022. It was discovered that Matlab would reference the most recent installation of .NET (9.0 in my case) which was installed by VS 2022. When I set "core" as the environment in Matlab (dotnetenv("core")), I would then make the .NET assembly visible to Matlab using NET.addAssembly("insert path here"). When Matlab got to this step, it would buffer for about 10 seconds then crash immediately with no crash report. Getting help from my local IT, we pin pointed it to the .NET 9.0 install causing the problem.
To get around this, you can either uninstall 9.0 or set up an environment variable in your system properties called "DOTNET_ROOT" that can force a path to be referenced.
So I would like to ask if anyone else has faced this issue in Matlab? Is it an unexpected error that needs an error handle? I am naive to .net, and really only know the particular dll I interact with to do my methods, etc.Note: Workaround is to remove .NET 9.0 from PC to resolve conflicts with 6.0.
This might be a .NET issue as a whole, but I only see it using Matlab, so I am posting here to help others out facing the same issues.
I have a .dll from one of the groups I work with for communicating to our devices. The .dll was built in .NET 6.0 (core) (x64). I have been able to use it in the past in Matlab, but have now run into issues since installing Visual Studio 2022. It was discovered that Matlab would reference the most recent installation of .NET (9.0 in my case) which was installed by VS 2022. When I set "core" as the environment in Matlab (dotnetenv("core")), I would then make the .NET assembly visible to Matlab using NET.addAssembly("insert path here"). When Matlab got to this step, it would buffer for about 10 seconds then crash immediately with no crash report. Getting help from my local IT, we pin pointed it to the .NET 9.0 install causing the problem.
To get around this, you can either uninstall 9.0 or set up an environment variable in your system properties called "DOTNET_ROOT" that can force a path to be referenced.
So I would like to ask if anyone else has faced this issue in Matlab? Is it an unexpected error that needs an error handle? I am naive to .net, and really only know the particular dll I interact with to do my methods, etc. Note: Workaround is to remove .NET 9.0 from PC to resolve conflicts with 6.0.
This might be a .NET issue as a whole, but I only see it using Matlab, so I am posting here to help others out facing the same issues.
I have a .dll from one of the groups I work with for communicating to our devices. The .dll was built in .NET 6.0 (core) (x64). I have been able to use it in the past in Matlab, but have now run into issues since installing Visual Studio 2022. It was discovered that Matlab would reference the most recent installation of .NET (9.0 in my case) which was installed by VS 2022. When I set "core" as the environment in Matlab (dotnetenv("core")), I would then make the .NET assembly visible to Matlab using NET.addAssembly("insert path here"). When Matlab got to this step, it would buffer for about 10 seconds then crash immediately with no crash report. Getting help from my local IT, we pin pointed it to the .NET 9.0 install causing the problem.
To get around this, you can either uninstall 9.0 or set up an environment variable in your system properties called "DOTNET_ROOT" that can force a path to be referenced.
So I would like to ask if anyone else has faced this issue in Matlab? Is it an unexpected error that needs an error handle? I am naive to .net, and really only know the particular dll I interact with to do my methods, etc. .net MATLAB Answers — New Questions
Large Gregorian Antenna simulations at high frequency
If I have a large Gregorian antenna (2-3 meter) and need to operate it in frequency range 20/30 GHz, I get a problem of out of memory and need RAM in range of 200G or more !! Is there a solution to this issue? By decreasing number of iterations or decrease accuracy needed ?If I have a large Gregorian antenna (2-3 meter) and need to operate it in frequency range 20/30 GHz, I get a problem of out of memory and need RAM in range of 200G or more !! Is there a solution to this issue? By decreasing number of iterations or decrease accuracy needed ? If I have a large Gregorian antenna (2-3 meter) and need to operate it in frequency range 20/30 GHz, I get a problem of out of memory and need RAM in range of 200G or more !! Is there a solution to this issue? By decreasing number of iterations or decrease accuracy needed ? antenna, high frequency MATLAB Answers — New Questions
VPP Virtual Power Plants model SIMULINK
Hello everyone! Can I have some files about VPP Virtual Power Plants research for reference during my studies? Please help me.Hello everyone! Can I have some files about VPP Virtual Power Plants research for reference during my studies? Please help me. Hello everyone! Can I have some files about VPP Virtual Power Plants research for reference during my studies? Please help me. vpp, model MATLAB Answers — New Questions
lsqlin and its constraints
Hi,
How does MATLAB impose the Upper and Lower Bound on the
unknowns in the lsqlin routine?
Does it build a quadratic format of the constraints and ads it to the solution?!Hi,
How does MATLAB impose the Upper and Lower Bound on the
unknowns in the lsqlin routine?
Does it build a quadratic format of the constraints and ads it to the solution?! Hi,
How does MATLAB impose the Upper and Lower Bound on the
unknowns in the lsqlin routine?
Does it build a quadratic format of the constraints and ads it to the solution?! optimization, curve fitting MATLAB Answers — New Questions