Tag Archives: matlab
How to interpolate values given a starting and end point
I have a voltmeter that I was using to measure voltage on a battery, unfortunatly it wasnt working properly and Im not able to do the test again. Before and after I ran the test I tested the voltage, so I know the real starting (50.6V) and ending (50.3V). My voltmeter recorded the power draw correctly but the values are off, they hover around 18V, how do I interpolate the bad values with a known starting and end point?
Example:
I know its 50.6 to 50.3 and my recordings are 18.2 to 17.9
I want the readings to be 50.6, 50.5, 50.4, 50.3 instead of 18.2, 18.1, 18.0, 17.9. I cant just add the difference because power draw wasnt exactly linear so Im trying to use the interp1 function but it isnt working for me. Thanks!I have a voltmeter that I was using to measure voltage on a battery, unfortunatly it wasnt working properly and Im not able to do the test again. Before and after I ran the test I tested the voltage, so I know the real starting (50.6V) and ending (50.3V). My voltmeter recorded the power draw correctly but the values are off, they hover around 18V, how do I interpolate the bad values with a known starting and end point?
Example:
I know its 50.6 to 50.3 and my recordings are 18.2 to 17.9
I want the readings to be 50.6, 50.5, 50.4, 50.3 instead of 18.2, 18.1, 18.0, 17.9. I cant just add the difference because power draw wasnt exactly linear so Im trying to use the interp1 function but it isnt working for me. Thanks! I have a voltmeter that I was using to measure voltage on a battery, unfortunatly it wasnt working properly and Im not able to do the test again. Before and after I ran the test I tested the voltage, so I know the real starting (50.6V) and ending (50.3V). My voltmeter recorded the power draw correctly but the values are off, they hover around 18V, how do I interpolate the bad values with a known starting and end point?
Example:
I know its 50.6 to 50.3 and my recordings are 18.2 to 17.9
I want the readings to be 50.6, 50.5, 50.4, 50.3 instead of 18.2, 18.1, 18.0, 17.9. I cant just add the difference because power draw wasnt exactly linear so Im trying to use the interp1 function but it isnt working for me. Thanks! volts MATLAB Answers — New Questions
Why do I receive License Manager Error -18?
I am getting the following error message:
ERROR: License checkout failed. License server does not support this FEATURE. License Manager Error -18I am getting the following error message:
ERROR: License checkout failed. License server does not support this FEATURE. License Manager Error -18 I am getting the following error message:
ERROR: License checkout failed. License server does not support this FEATURE. License Manager Error -18 MATLAB Answers — New Questions
How can I backup a Polyspace Metrics Server before uninstalling it?
I’m temporarily uninstalling my Polyspace Metrics Server, and I’d like to backup the correct files in the event that I use Polyspace Metrics in the future. What exactly do I need in order to restart this server?I’m temporarily uninstalling my Polyspace Metrics Server, and I’d like to backup the correct files in the event that I use Polyspace Metrics in the future. What exactly do I need in order to restart this server? I’m temporarily uninstalling my Polyspace Metrics Server, and I’d like to backup the correct files in the event that I use Polyspace Metrics in the future. What exactly do I need in order to restart this server? polyspace, metrics, backup, server, file MATLAB Answers — New Questions
Flow rate discrepancy between upstream and downstream of orifice model.
I am verifying the flow rate before and after orifice model measured by "Flow Rate Sensor".
The target value of flow rate is 13.2 gpm with diffential pressure 2950 psid and orifice model of orifice area is set to get this flow rate.
Simulation Retuls of flow rate
Before orifice: 13.08 gpm
After orifice: 13.26 gpm
Is there any solution or what is the root cause of this discrepancy?I am verifying the flow rate before and after orifice model measured by "Flow Rate Sensor".
The target value of flow rate is 13.2 gpm with diffential pressure 2950 psid and orifice model of orifice area is set to get this flow rate.
Simulation Retuls of flow rate
Before orifice: 13.08 gpm
After orifice: 13.26 gpm
Is there any solution or what is the root cause of this discrepancy? I am verifying the flow rate before and after orifice model measured by "Flow Rate Sensor".
The target value of flow rate is 13.2 gpm with diffential pressure 2950 psid and orifice model of orifice area is set to get this flow rate.
Simulation Retuls of flow rate
Before orifice: 13.08 gpm
After orifice: 13.26 gpm
Is there any solution or what is the root cause of this discrepancy? flow rate MATLAB Answers — New Questions
LSTM TO STRING CATEGORICAL LABELS
Hi Please help with with this code, there are two questions,
Looks like my LSTM cannot achieve any better accuracy – what could be the cause?
At the very end of the code, I wanted to to plot a confusion chart, – 1 – I used a for loop to capture the predicted labels from the trained network, is there a one line command for this type of data structure?
Still on the confusion chart, what would be the best way to create the true labels set, I see the one I used in the function call for confusion chart is really incomplete, I am expecting the true labels set to be 40 x 5 matrix just like the test set.Hi Please help with with this code, there are two questions,
Looks like my LSTM cannot achieve any better accuracy – what could be the cause?
At the very end of the code, I wanted to to plot a confusion chart, – 1 – I used a for loop to capture the predicted labels from the trained network, is there a one line command for this type of data structure?
Still on the confusion chart, what would be the best way to create the true labels set, I see the one I used in the function call for confusion chart is really incomplete, I am expecting the true labels set to be 40 x 5 matrix just like the test set. Hi Please help with with this code, there are two questions,
Looks like my LSTM cannot achieve any better accuracy – what could be the cause?
At the very end of the code, I wanted to to plot a confusion chart, – 1 – I used a for loop to capture the predicted labels from the trained network, is there a one line command for this type of data structure?
Still on the confusion chart, what would be the best way to create the true labels set, I see the one I used in the function call for confusion chart is really incomplete, I am expecting the true labels set to be 40 x 5 matrix just like the test set. lstm MATLAB Answers — New Questions
Why do I receive a “Permission denied” error when trying to install with the MATLAB Package Manager?
When trying to install MathWorks products with the MATLAB Package Manager (MPM), I encounter an error like the following:
/tmp/path/to/mpm: Permission denied
How can I resolve this error?When trying to install MathWorks products with the MATLAB Package Manager (MPM), I encounter an error like the following:
/tmp/path/to/mpm: Permission denied
How can I resolve this error? When trying to install MathWorks products with the MATLAB Package Manager (MPM), I encounter an error like the following:
/tmp/path/to/mpm: Permission denied
How can I resolve this error? MATLAB Answers — New Questions
Training 4 TD3 RL Agents in Simulink to control Buck Converter . They need new observations, initialized from Buck Converter outputs. How to learn continuously from 1s to 5s?
I am trying to train 4 TD3 RL Agents in the Simulink Environment. Each Agent is supposed to control the output voltage of a Buck Converter by sending its action signal to the input of the Buck Converter (as a reference voltage). For the sake of improving the learning process and enhancing the exploration of the agents, I want to initiate the environment such that at the beginning of each training episode, the agents observe a new set of observations. The issue is that all 9 elements of the observation vectors depend on the output voltages of the Buck Converters (the Actions). So I need to initialize the model at the beginning of each training episode by initializing the inputs of the Buck Converters, then as the agent starts sampling from the environment, replace the initilizing parameters with the actions of the agents. To implement that, I have put the RL Agent blocks in the Triggered Subsystems, and connected their outputs to Swich Blocks for alternating between the initializing parameter and the output of Triggered Subsystems (Action Signals). from the beginning of the episode till the second 1 of the simulation, the model gets initialize with the initializing parameter, then in the second 1, switch will work, and triggered subsystem will be activated. My question is: How can I modify my code so that the agents start the learning process from seconde 1 till the end of simulation time at seconde 5 (4 seconds of training for each episode)?
@ Tzorakoleftherakis I would greatly appreciate your kind help.I am trying to train 4 TD3 RL Agents in the Simulink Environment. Each Agent is supposed to control the output voltage of a Buck Converter by sending its action signal to the input of the Buck Converter (as a reference voltage). For the sake of improving the learning process and enhancing the exploration of the agents, I want to initiate the environment such that at the beginning of each training episode, the agents observe a new set of observations. The issue is that all 9 elements of the observation vectors depend on the output voltages of the Buck Converters (the Actions). So I need to initialize the model at the beginning of each training episode by initializing the inputs of the Buck Converters, then as the agent starts sampling from the environment, replace the initilizing parameters with the actions of the agents. To implement that, I have put the RL Agent blocks in the Triggered Subsystems, and connected their outputs to Swich Blocks for alternating between the initializing parameter and the output of Triggered Subsystems (Action Signals). from the beginning of the episode till the second 1 of the simulation, the model gets initialize with the initializing parameter, then in the second 1, switch will work, and triggered subsystem will be activated. My question is: How can I modify my code so that the agents start the learning process from seconde 1 till the end of simulation time at seconde 5 (4 seconds of training for each episode)?
@ Tzorakoleftherakis I would greatly appreciate your kind help. I am trying to train 4 TD3 RL Agents in the Simulink Environment. Each Agent is supposed to control the output voltage of a Buck Converter by sending its action signal to the input of the Buck Converter (as a reference voltage). For the sake of improving the learning process and enhancing the exploration of the agents, I want to initiate the environment such that at the beginning of each training episode, the agents observe a new set of observations. The issue is that all 9 elements of the observation vectors depend on the output voltages of the Buck Converters (the Actions). So I need to initialize the model at the beginning of each training episode by initializing the inputs of the Buck Converters, then as the agent starts sampling from the environment, replace the initilizing parameters with the actions of the agents. To implement that, I have put the RL Agent blocks in the Triggered Subsystems, and connected their outputs to Swich Blocks for alternating between the initializing parameter and the output of Triggered Subsystems (Action Signals). from the beginning of the episode till the second 1 of the simulation, the model gets initialize with the initializing parameter, then in the second 1, switch will work, and triggered subsystem will be activated. My question is: How can I modify my code so that the agents start the learning process from seconde 1 till the end of simulation time at seconde 5 (4 seconds of training for each episode)?
@ Tzorakoleftherakis I would greatly appreciate your kind help. reinforcement learning, td3 agents, buck converter, observation initilization MATLAB Answers — New Questions
Does the MATLAB Package Manager support proxy servers?
Does the MATLAB Package Manager (MPM) support downloading product files for MathWorks products through a proxy?Does the MATLAB Package Manager (MPM) support downloading product files for MathWorks products through a proxy? Does the MATLAB Package Manager (MPM) support downloading product files for MathWorks products through a proxy? MATLAB Answers — New Questions
Why do I receive the error “Error: Download failed. Check the network connection and retry.” when installing using the MATLAB Package Manager?
When trying to install MathWorks products with the MATLAB Package Manager (MPM), I encounter an error like the following:
Error: Download failed. Check the network connection and retry.
How do I resolve this?When trying to install MathWorks products with the MATLAB Package Manager (MPM), I encounter an error like the following:
Error: Download failed. Check the network connection and retry.
How do I resolve this? When trying to install MathWorks products with the MATLAB Package Manager (MPM), I encounter an error like the following:
Error: Download failed. Check the network connection and retry.
How do I resolve this? MATLAB Answers — New Questions
How to distinguish pressing cancel vs entering an empty string in inputdlg?
I have an input dialog box that will reopen if an invalid name is entered (it will close if more than 5 attempts is made). It is asking for a name to create a file with.
I want the user to be able to press "cancel" or the "x" (windows close button) and have the program exit, but I also want the user to not type anything and press "ok" and have it count as an incorrect attempt and reopen the box.
However, the only way I found people saying to use this is to check if the input is empty, if it is to break. However, this does not distinguish between meaningfully enterring an empty string and pressing cancel/x.
Is there a way to do what I am trying to do?
Also, if there is a better way to write the code in general, please let me know. I am open to improvements and criticism. This is my first MATLAB script I’ve written. It’s been a journey trying to learn the language/script (coming only from standard C).
Here is the snippet from my code:
while badFileName == true
attemptsLeft = num2str(5 – errorCounter);
outputName = inputdlg([‘Please enter a file name. Do not use spaces! Attempts left: ‘ attemptsLeft],’Output File Creation’);
if isempty(outputName)
return;
end
outputName = string(outputName);
badFileName = contains(outputName,illegalCharacters);
errorCounter = errorCounter+1;
if errorCounter >= 5
break
end
endI have an input dialog box that will reopen if an invalid name is entered (it will close if more than 5 attempts is made). It is asking for a name to create a file with.
I want the user to be able to press "cancel" or the "x" (windows close button) and have the program exit, but I also want the user to not type anything and press "ok" and have it count as an incorrect attempt and reopen the box.
However, the only way I found people saying to use this is to check if the input is empty, if it is to break. However, this does not distinguish between meaningfully enterring an empty string and pressing cancel/x.
Is there a way to do what I am trying to do?
Also, if there is a better way to write the code in general, please let me know. I am open to improvements and criticism. This is my first MATLAB script I’ve written. It’s been a journey trying to learn the language/script (coming only from standard C).
Here is the snippet from my code:
while badFileName == true
attemptsLeft = num2str(5 – errorCounter);
outputName = inputdlg([‘Please enter a file name. Do not use spaces! Attempts left: ‘ attemptsLeft],’Output File Creation’);
if isempty(outputName)
return;
end
outputName = string(outputName);
badFileName = contains(outputName,illegalCharacters);
errorCounter = errorCounter+1;
if errorCounter >= 5
break
end
end I have an input dialog box that will reopen if an invalid name is entered (it will close if more than 5 attempts is made). It is asking for a name to create a file with.
I want the user to be able to press "cancel" or the "x" (windows close button) and have the program exit, but I also want the user to not type anything and press "ok" and have it count as an incorrect attempt and reopen the box.
However, the only way I found people saying to use this is to check if the input is empty, if it is to break. However, this does not distinguish between meaningfully enterring an empty string and pressing cancel/x.
Is there a way to do what I am trying to do?
Also, if there is a better way to write the code in general, please let me know. I am open to improvements and criticism. This is my first MATLAB script I’ve written. It’s been a journey trying to learn the language/script (coming only from standard C).
Here is the snippet from my code:
while badFileName == true
attemptsLeft = num2str(5 – errorCounter);
outputName = inputdlg([‘Please enter a file name. Do not use spaces! Attempts left: ‘ attemptsLeft],’Output File Creation’);
if isempty(outputName)
return;
end
outputName = string(outputName);
badFileName = contains(outputName,illegalCharacters);
errorCounter = errorCounter+1;
if errorCounter >= 5
break
end
end inputdlg, matlab gui, input, loops MATLAB Answers — New Questions
What is MATLAB doing when adding multiple ZPK transfer functions together?
I am trying to add multiple zpk transfer functions by directly accessing the zeros, poles, and gains without the use of the "parallel" or "+" operations (for runtime reduction), and I was wondering what "+" does:
zero1 = [1, 2];
pole1 = [3, 4];
gain1 = 2;
tf1 = zpk(zero1, pole1, gain1)
% tf1 =
%
% 2 (s-1) (s-2)
% ————-
% (s-3) (s-4)
zero2 = [-1, -2];
pole2 = [-3, -4];
gain2 = -2;
tf2 = zpk(zero2, pole2, gain2)
% tf2 =
%
% -2 (s+1) (s+2)
% ————–
% (s+3) (s+4)
tf = tf1 + tf2
% tf =
%
% 16 s (s-2.345) (s+2.345)
% ————————
% (s-3) (s-4) (s+3) (s+4)
I googled how to add two ZPK transfer functions and it said that it’s simply linearly adding them together but Matlab is definitely doing something different (as "tf" has a zero at +/- 2.345 when neither "tf1" nor "tf2" have those zeros)I am trying to add multiple zpk transfer functions by directly accessing the zeros, poles, and gains without the use of the "parallel" or "+" operations (for runtime reduction), and I was wondering what "+" does:
zero1 = [1, 2];
pole1 = [3, 4];
gain1 = 2;
tf1 = zpk(zero1, pole1, gain1)
% tf1 =
%
% 2 (s-1) (s-2)
% ————-
% (s-3) (s-4)
zero2 = [-1, -2];
pole2 = [-3, -4];
gain2 = -2;
tf2 = zpk(zero2, pole2, gain2)
% tf2 =
%
% -2 (s+1) (s+2)
% ————–
% (s+3) (s+4)
tf = tf1 + tf2
% tf =
%
% 16 s (s-2.345) (s+2.345)
% ————————
% (s-3) (s-4) (s+3) (s+4)
I googled how to add two ZPK transfer functions and it said that it’s simply linearly adding them together but Matlab is definitely doing something different (as "tf" has a zero at +/- 2.345 when neither "tf1" nor "tf2" have those zeros) I am trying to add multiple zpk transfer functions by directly accessing the zeros, poles, and gains without the use of the "parallel" or "+" operations (for runtime reduction), and I was wondering what "+" does:
zero1 = [1, 2];
pole1 = [3, 4];
gain1 = 2;
tf1 = zpk(zero1, pole1, gain1)
% tf1 =
%
% 2 (s-1) (s-2)
% ————-
% (s-3) (s-4)
zero2 = [-1, -2];
pole2 = [-3, -4];
gain2 = -2;
tf2 = zpk(zero2, pole2, gain2)
% tf2 =
%
% -2 (s+1) (s+2)
% ————–
% (s+3) (s+4)
tf = tf1 + tf2
% tf =
%
% 16 s (s-2.345) (s+2.345)
% ————————
% (s-3) (s-4) (s+3) (s+4)
I googled how to add two ZPK transfer functions and it said that it’s simply linearly adding them together but Matlab is definitely doing something different (as "tf" has a zero at +/- 2.345 when neither "tf1" nor "tf2" have those zeros) zpk, add MATLAB Answers — New Questions
fminunc limit step size
I am exploring fminunc with a 2-D but challenging function (see below), with a narrow and curved "canyon". Some times it works fine, descending to the bottom of the canyon and following it until the minimum. But at other starting points it makes a huge initial step that brings it nowhere. Isn’t there any way to limit the step size? Notice that first and second derivatives are analytic, i.e. no finite differences.
% spiralFuncion.m
% A challenging function to minimize in 2D
% JMS, Jun.2024
clear all
% Find function in a mesh
dx = 0.05;
xmax = 2.5;
x = -xmax:dx:xmax;
nx = numel(x);
[x,y] = ndgrid(x,x);
z = myfunc([x(:)’;y(:)’]);
z = reshape(z,nx,nx);
% Find minimum value at mesh points
i0 = find(z(:)==min(z(:)));
xmin = [x(i0),y(i0)]
zmin = z(i0)
% Plot function using surf and contour
figure(1)
contour(x’,y’,z’,20), axis equal
hold on, plot(xmin(1),xmin(2),’x’,’MarkerSize’,10), hold off
grid on
figure(2)
surf(x’,y’,z’)
grid on
% Set minimization options
opt = optimoptions(‘fminunc’);
opt = optimoptions(opt,’Algorithm’,’trust-region’);
opt = optimoptions(opt,’SubproblemAlgorithm’,’factorization’);
opt = optimoptions(opt,’SpecifyObjectiveGradient’,true);
opt = optimoptions(opt,’HessianFcn’,’objective’);
opt = optimoptions(opt,’MaxIterations’,1e3);
opt = optimoptions(opt,’MaxFunctionEvaluations’,1e3);
opt = optimoptions(opt,’Display’,’none’);
% Minimize function starting from a random point
x0 = randn(2,1);
[x,f,exitflag,output] = fminunc(@myfunc,x0,opt);
niter = output.iterations
fprintf(‘n%sn’,output.message)
% Find minimization path
for iter = 1:niter
opt = optimoptions(opt,’MaxIterations’,iter);
xpath(:,iter) = fminunc(@myfunc,x0,opt);
end
% opt = optimoptions(opt,’MaxIterations’,1);
% xpath(:,1) = fminunc(@myfunc,x0,opt);
% for iter = 2:niter
% xpath(:,iter) = fminunc(@myfunc,xpath(:,iter-1),opt);
% end
% Plot minimization path
figure(1)
hold on,
plot([x0(1),xpath(1,:)],[x0(2),xpath(2,:)],’r.-‘,’LineWidth’,2,’MarkerSize’,15)
plot(x(1),x(2),’.b’,’MarkerSize’,20)
hold off
%———————————
function [f,DfDx,D2fDx2] = myfunc(x)
a = 1; % smaller a => harder to minimize
r = sqrt(x(1,:).^2+x(2,:).^2);
s = atan2(x(2,:),x(1,:));
rs = 2*pi*r+s;
f = r.*exp(-a*r).*cos(rs);
% Firts derivatives
ts = x(2,:)./x(1,:); % ts=tan(s)
trs = tan(rs);
DtsDs = 1+ts.^2;
DtrsDrs = 1+trs.^2;
DsDts = 1./DtsDs;
DrsDr = 2*pi;
DrsDs = 1;
DrDx = x./r;
DtsDx = [ -x(2,:)./x(1,:).^2; 1./x(1,:) ];
DsDx = DsDts.*DtsDx;
DfDr = f./r – a*f – f.*trs.*DrsDr;
DfDs = -f.*trs.*DrsDs;
DfDx = DfDr.*DrDx + DfDs.*DsDx;
% Second derivatives
nx = size(x,2);
D2tsDs2 = 2*ts.*DtsDs;
D2trsDrs2 = 2*trs.*DtrsDrs;
D2rsDr2 = 0;
D2rsDs2 = 0;
D2rsDrDs = 0;
% note: d2x/dy2 = d(dy/dx)^-1/dy = d(dy/dx)^-1/dx * dx/dy =
% = -(dy/dx)^-2 * d2y/dx2 * (dy/dx)^-1 = -(dy/dx)^-3 * d2y/dx2
D2sDts2 = -D2tsDs2./DtsDs.^3;
D2fDr2 = DfDr./r – f./r.^2 – a*DfDr – DfDr.*trs.*DrsDr …
– f.*DtrsDrs.*DrsDr.^2 – f.*trs.*D2rsDr2;
D2fDs2 = – DfDs.*trs.*DrsDs – f.*DtrsDrs.*DrsDs.^2 …
– f.*trs.*D2rsDs2;
D2fDrDs = – DfDr.*trs.*DrsDs – f.*DtrsDrs.*DrsDr.*DrsDs …
– f.*trs.*D2rsDrDs;
for ix = 1:nx
D2rDx2 = eye(2)/r(ix) – x(:,ix).*x(:,ix)’/r(ix)^3;
D2tsDx2 = [ +2*x(2,ix)/x(1,ix).^3, -1/x(1,ix)^2
-1/x(1,ix).^2, 0 ];
D2sDx2 = D2sDts2(ix)*DtsDx(:,ix).*DtsDx(:,ix)’ + DsDts(ix)*D2tsDx2;
D2fDx2(:,:,ix) = D2fDr2(ix) *DrDx(:,ix).*DrDx(:,ix)’ …
+ D2fDs2(ix) *DsDx(:,ix).*DsDx(:,ix)’ …
+ D2fDrDs(ix)*DrDx(:,ix).*DsDx(:,ix)’ …
+ D2fDrDs(ix)*DsDx(:,ix).*DrDx(:,ix)’ …
+ DfDr(ix)*D2rDx2 + DfDs(ix)*D2sDx2;
end
endI am exploring fminunc with a 2-D but challenging function (see below), with a narrow and curved "canyon". Some times it works fine, descending to the bottom of the canyon and following it until the minimum. But at other starting points it makes a huge initial step that brings it nowhere. Isn’t there any way to limit the step size? Notice that first and second derivatives are analytic, i.e. no finite differences.
% spiralFuncion.m
% A challenging function to minimize in 2D
% JMS, Jun.2024
clear all
% Find function in a mesh
dx = 0.05;
xmax = 2.5;
x = -xmax:dx:xmax;
nx = numel(x);
[x,y] = ndgrid(x,x);
z = myfunc([x(:)’;y(:)’]);
z = reshape(z,nx,nx);
% Find minimum value at mesh points
i0 = find(z(:)==min(z(:)));
xmin = [x(i0),y(i0)]
zmin = z(i0)
% Plot function using surf and contour
figure(1)
contour(x’,y’,z’,20), axis equal
hold on, plot(xmin(1),xmin(2),’x’,’MarkerSize’,10), hold off
grid on
figure(2)
surf(x’,y’,z’)
grid on
% Set minimization options
opt = optimoptions(‘fminunc’);
opt = optimoptions(opt,’Algorithm’,’trust-region’);
opt = optimoptions(opt,’SubproblemAlgorithm’,’factorization’);
opt = optimoptions(opt,’SpecifyObjectiveGradient’,true);
opt = optimoptions(opt,’HessianFcn’,’objective’);
opt = optimoptions(opt,’MaxIterations’,1e3);
opt = optimoptions(opt,’MaxFunctionEvaluations’,1e3);
opt = optimoptions(opt,’Display’,’none’);
% Minimize function starting from a random point
x0 = randn(2,1);
[x,f,exitflag,output] = fminunc(@myfunc,x0,opt);
niter = output.iterations
fprintf(‘n%sn’,output.message)
% Find minimization path
for iter = 1:niter
opt = optimoptions(opt,’MaxIterations’,iter);
xpath(:,iter) = fminunc(@myfunc,x0,opt);
end
% opt = optimoptions(opt,’MaxIterations’,1);
% xpath(:,1) = fminunc(@myfunc,x0,opt);
% for iter = 2:niter
% xpath(:,iter) = fminunc(@myfunc,xpath(:,iter-1),opt);
% end
% Plot minimization path
figure(1)
hold on,
plot([x0(1),xpath(1,:)],[x0(2),xpath(2,:)],’r.-‘,’LineWidth’,2,’MarkerSize’,15)
plot(x(1),x(2),’.b’,’MarkerSize’,20)
hold off
%———————————
function [f,DfDx,D2fDx2] = myfunc(x)
a = 1; % smaller a => harder to minimize
r = sqrt(x(1,:).^2+x(2,:).^2);
s = atan2(x(2,:),x(1,:));
rs = 2*pi*r+s;
f = r.*exp(-a*r).*cos(rs);
% Firts derivatives
ts = x(2,:)./x(1,:); % ts=tan(s)
trs = tan(rs);
DtsDs = 1+ts.^2;
DtrsDrs = 1+trs.^2;
DsDts = 1./DtsDs;
DrsDr = 2*pi;
DrsDs = 1;
DrDx = x./r;
DtsDx = [ -x(2,:)./x(1,:).^2; 1./x(1,:) ];
DsDx = DsDts.*DtsDx;
DfDr = f./r – a*f – f.*trs.*DrsDr;
DfDs = -f.*trs.*DrsDs;
DfDx = DfDr.*DrDx + DfDs.*DsDx;
% Second derivatives
nx = size(x,2);
D2tsDs2 = 2*ts.*DtsDs;
D2trsDrs2 = 2*trs.*DtrsDrs;
D2rsDr2 = 0;
D2rsDs2 = 0;
D2rsDrDs = 0;
% note: d2x/dy2 = d(dy/dx)^-1/dy = d(dy/dx)^-1/dx * dx/dy =
% = -(dy/dx)^-2 * d2y/dx2 * (dy/dx)^-1 = -(dy/dx)^-3 * d2y/dx2
D2sDts2 = -D2tsDs2./DtsDs.^3;
D2fDr2 = DfDr./r – f./r.^2 – a*DfDr – DfDr.*trs.*DrsDr …
– f.*DtrsDrs.*DrsDr.^2 – f.*trs.*D2rsDr2;
D2fDs2 = – DfDs.*trs.*DrsDs – f.*DtrsDrs.*DrsDs.^2 …
– f.*trs.*D2rsDs2;
D2fDrDs = – DfDr.*trs.*DrsDs – f.*DtrsDrs.*DrsDr.*DrsDs …
– f.*trs.*D2rsDrDs;
for ix = 1:nx
D2rDx2 = eye(2)/r(ix) – x(:,ix).*x(:,ix)’/r(ix)^3;
D2tsDx2 = [ +2*x(2,ix)/x(1,ix).^3, -1/x(1,ix)^2
-1/x(1,ix).^2, 0 ];
D2sDx2 = D2sDts2(ix)*DtsDx(:,ix).*DtsDx(:,ix)’ + DsDts(ix)*D2tsDx2;
D2fDx2(:,:,ix) = D2fDr2(ix) *DrDx(:,ix).*DrDx(:,ix)’ …
+ D2fDs2(ix) *DsDx(:,ix).*DsDx(:,ix)’ …
+ D2fDrDs(ix)*DrDx(:,ix).*DsDx(:,ix)’ …
+ D2fDrDs(ix)*DsDx(:,ix).*DrDx(:,ix)’ …
+ DfDr(ix)*D2rDx2 + DfDs(ix)*D2sDx2;
end
end I am exploring fminunc with a 2-D but challenging function (see below), with a narrow and curved "canyon". Some times it works fine, descending to the bottom of the canyon and following it until the minimum. But at other starting points it makes a huge initial step that brings it nowhere. Isn’t there any way to limit the step size? Notice that first and second derivatives are analytic, i.e. no finite differences.
% spiralFuncion.m
% A challenging function to minimize in 2D
% JMS, Jun.2024
clear all
% Find function in a mesh
dx = 0.05;
xmax = 2.5;
x = -xmax:dx:xmax;
nx = numel(x);
[x,y] = ndgrid(x,x);
z = myfunc([x(:)’;y(:)’]);
z = reshape(z,nx,nx);
% Find minimum value at mesh points
i0 = find(z(:)==min(z(:)));
xmin = [x(i0),y(i0)]
zmin = z(i0)
% Plot function using surf and contour
figure(1)
contour(x’,y’,z’,20), axis equal
hold on, plot(xmin(1),xmin(2),’x’,’MarkerSize’,10), hold off
grid on
figure(2)
surf(x’,y’,z’)
grid on
% Set minimization options
opt = optimoptions(‘fminunc’);
opt = optimoptions(opt,’Algorithm’,’trust-region’);
opt = optimoptions(opt,’SubproblemAlgorithm’,’factorization’);
opt = optimoptions(opt,’SpecifyObjectiveGradient’,true);
opt = optimoptions(opt,’HessianFcn’,’objective’);
opt = optimoptions(opt,’MaxIterations’,1e3);
opt = optimoptions(opt,’MaxFunctionEvaluations’,1e3);
opt = optimoptions(opt,’Display’,’none’);
% Minimize function starting from a random point
x0 = randn(2,1);
[x,f,exitflag,output] = fminunc(@myfunc,x0,opt);
niter = output.iterations
fprintf(‘n%sn’,output.message)
% Find minimization path
for iter = 1:niter
opt = optimoptions(opt,’MaxIterations’,iter);
xpath(:,iter) = fminunc(@myfunc,x0,opt);
end
% opt = optimoptions(opt,’MaxIterations’,1);
% xpath(:,1) = fminunc(@myfunc,x0,opt);
% for iter = 2:niter
% xpath(:,iter) = fminunc(@myfunc,xpath(:,iter-1),opt);
% end
% Plot minimization path
figure(1)
hold on,
plot([x0(1),xpath(1,:)],[x0(2),xpath(2,:)],’r.-‘,’LineWidth’,2,’MarkerSize’,15)
plot(x(1),x(2),’.b’,’MarkerSize’,20)
hold off
%———————————
function [f,DfDx,D2fDx2] = myfunc(x)
a = 1; % smaller a => harder to minimize
r = sqrt(x(1,:).^2+x(2,:).^2);
s = atan2(x(2,:),x(1,:));
rs = 2*pi*r+s;
f = r.*exp(-a*r).*cos(rs);
% Firts derivatives
ts = x(2,:)./x(1,:); % ts=tan(s)
trs = tan(rs);
DtsDs = 1+ts.^2;
DtrsDrs = 1+trs.^2;
DsDts = 1./DtsDs;
DrsDr = 2*pi;
DrsDs = 1;
DrDx = x./r;
DtsDx = [ -x(2,:)./x(1,:).^2; 1./x(1,:) ];
DsDx = DsDts.*DtsDx;
DfDr = f./r – a*f – f.*trs.*DrsDr;
DfDs = -f.*trs.*DrsDs;
DfDx = DfDr.*DrDx + DfDs.*DsDx;
% Second derivatives
nx = size(x,2);
D2tsDs2 = 2*ts.*DtsDs;
D2trsDrs2 = 2*trs.*DtrsDrs;
D2rsDr2 = 0;
D2rsDs2 = 0;
D2rsDrDs = 0;
% note: d2x/dy2 = d(dy/dx)^-1/dy = d(dy/dx)^-1/dx * dx/dy =
% = -(dy/dx)^-2 * d2y/dx2 * (dy/dx)^-1 = -(dy/dx)^-3 * d2y/dx2
D2sDts2 = -D2tsDs2./DtsDs.^3;
D2fDr2 = DfDr./r – f./r.^2 – a*DfDr – DfDr.*trs.*DrsDr …
– f.*DtrsDrs.*DrsDr.^2 – f.*trs.*D2rsDr2;
D2fDs2 = – DfDs.*trs.*DrsDs – f.*DtrsDrs.*DrsDs.^2 …
– f.*trs.*D2rsDs2;
D2fDrDs = – DfDr.*trs.*DrsDs – f.*DtrsDrs.*DrsDr.*DrsDs …
– f.*trs.*D2rsDrDs;
for ix = 1:nx
D2rDx2 = eye(2)/r(ix) – x(:,ix).*x(:,ix)’/r(ix)^3;
D2tsDx2 = [ +2*x(2,ix)/x(1,ix).^3, -1/x(1,ix)^2
-1/x(1,ix).^2, 0 ];
D2sDx2 = D2sDts2(ix)*DtsDx(:,ix).*DtsDx(:,ix)’ + DsDts(ix)*D2tsDx2;
D2fDx2(:,:,ix) = D2fDr2(ix) *DrDx(:,ix).*DrDx(:,ix)’ …
+ D2fDs2(ix) *DsDx(:,ix).*DsDx(:,ix)’ …
+ D2fDrDs(ix)*DrDx(:,ix).*DsDx(:,ix)’ …
+ D2fDrDs(ix)*DsDx(:,ix).*DrDx(:,ix)’ …
+ DfDr(ix)*D2rDx2 + DfDs(ix)*D2sDx2;
end
end fminunc, step size MATLAB Answers — New Questions
How to use ‘goto’ statement?
I have the problem in the code segment:
if matchedRulesCount==0
goto(‘N’)
return
else
goto(‘N1’)
return
end
fprintf(‘Number of rules matched are:%dn’,matchedRulesCount);
%LABEL N
disp(‘No rule is fired.’);
%LABEL N1
choice=input(‘Do yo want to try once more? n0. For No.n1. For yes. n’);
I get the following error
??? Undefined function or method ‘goto’ for input arguments of type ‘char’.I have the problem in the code segment:
if matchedRulesCount==0
goto(‘N’)
return
else
goto(‘N1’)
return
end
fprintf(‘Number of rules matched are:%dn’,matchedRulesCount);
%LABEL N
disp(‘No rule is fired.’);
%LABEL N1
choice=input(‘Do yo want to try once more? n0. For No.n1. For yes. n’);
I get the following error
??? Undefined function or method ‘goto’ for input arguments of type ‘char’. I have the problem in the code segment:
if matchedRulesCount==0
goto(‘N’)
return
else
goto(‘N1’)
return
end
fprintf(‘Number of rules matched are:%dn’,matchedRulesCount);
%LABEL N
disp(‘No rule is fired.’);
%LABEL N1
choice=input(‘Do yo want to try once more? n0. For No.n1. For yes. n’);
I get the following error
??? Undefined function or method ‘goto’ for input arguments of type ‘char’. goto statement MATLAB Answers — New Questions
Uistack with a Graph and Subgraphs (GraphPlot)
Introduction. I have the following Graph and Subgraphs:
% Graph
s = [1 1 1 3 3 6 7 8 9 10 4 12 13 5 15 16 17 18 19 19 20 20 17 24 25 4 27 28 29];
t = [2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30];
G = graph(s,t);
% Node ID: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
G.Nodes.X = [2 1 3 2 4 4 5 4 5 4 5 1 3 3 5 6 7 6 8 7 9 8 9 8 9 10 1 1 0 1]’;
G.Nodes.Y = [2 1 3 9 3 5 8 12 13 18 21 15 18 21 0 2 8 12 15 20 10 22 18 5 4 4 5 8 12 23]’;
% Subgraphs
Gpath{1} = subgraph(G,shortestpath(G,4,14));
Gpath{2} = subgraph(G,shortestpath(G,4,26));
Gpath{3} = subgraph(G,shortestpath(G,4,30));
Gpath{4} = subgraph(G,shortestpath(G,3,10));
Gpath{5} = subgraph(G,shortestpath(G,3,28));
Gpath{6} = subgraph(G,shortestpath(G,3,21));
Gpath{7} = subgraph(G,shortestpath(G,17,12));
Gpath{8} = subgraph(G,shortestpath(G,17,23));
Gpath{9} = subgraph(G,shortestpath(G,17,26));
% Figure
hold on
p(1) = plot(G,’XData’,G.Nodes.X,’YData’,G.Nodes.Y,’LineWidth’,1,’EdgeColor’,’k’,’NodeColor’,’k’);
for i = [1 2 3]
p(2) = plot(Gpath{i},’XData’,Gpath{i}.Nodes.X,’YData’,Gpath{i}.Nodes.Y,’EdgeColor’,’y’,’NodeColor’,’y’);
p(2).NodeLabel = {};
p(2).EdgeAlpha = 1;
p(2).LineWidth = 5;
end
for i = [7 8 9]
p(3) = plot(Gpath{i},’XData’,Gpath{i}.Nodes.X,’YData’,Gpath{i}.Nodes.Y,’EdgeColor’,’g’,’NodeColor’,’g’);
p(3).NodeLabel = {};
p(3).EdgeAlpha = 1;
p(3).LineWidth = 9;
p(3).DisplayName = ‘Apple’;
end
for i = [4 5 6]
p(4) = plot(Gpath{i},’XData’,Gpath{i}.Nodes.X,’YData’,Gpath{i}.Nodes.Y,’EdgeColor’,’r’,’NodeColor’,’r’);
p(4).NodeLabel = {};
p(4).EdgeAlpha = 1;
p(4).LineWidth = 15;
p(4).DisplayName = ‘Strawberry’;
end
legend(p)
Just for clarity and a better understanding, here below I plot the GraphPlots separately as well:
Problem. When I try the to use uistack to change the visual stacking of the 4 GraphPlots, by bringing to the bottom both the GraphPlots called "Apple" (in green) and "Strawberry" (in red),
% Select the GraphPlots which have a non-empty "DisplayName", i.e. "Apple"
% and "Strawberry", and use Uistack
idx = find(~cellfun(@isempty,{p.DisplayName}));
p2 = uistack(p(idx),’bottom’)
legend(p2)
Only some Subgraphs are reshuffled, which means, to the best of my understanding, that uistack does not act on the 4 GraphPlots of "p", but, instead, on the 10 GraphPlots of "p2", i.e on the single Subgraphs:
Question. How to get what I expect, i.e. the following plot, where the 4 GraphPlots of "p" are reshuffled:
Note. Also, I have noticed that "p" and the "uistacked p", i.e. "p2", have different dimensions, and I guess it is the source of the problem:
p =
1×4 GraphPlot array:
GraphPlot GraphPlot GraphPlot GraphPlot
p2 =
10×1 GraphPlot array:
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlotIntroduction. I have the following Graph and Subgraphs:
% Graph
s = [1 1 1 3 3 6 7 8 9 10 4 12 13 5 15 16 17 18 19 19 20 20 17 24 25 4 27 28 29];
t = [2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30];
G = graph(s,t);
% Node ID: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
G.Nodes.X = [2 1 3 2 4 4 5 4 5 4 5 1 3 3 5 6 7 6 8 7 9 8 9 8 9 10 1 1 0 1]’;
G.Nodes.Y = [2 1 3 9 3 5 8 12 13 18 21 15 18 21 0 2 8 12 15 20 10 22 18 5 4 4 5 8 12 23]’;
% Subgraphs
Gpath{1} = subgraph(G,shortestpath(G,4,14));
Gpath{2} = subgraph(G,shortestpath(G,4,26));
Gpath{3} = subgraph(G,shortestpath(G,4,30));
Gpath{4} = subgraph(G,shortestpath(G,3,10));
Gpath{5} = subgraph(G,shortestpath(G,3,28));
Gpath{6} = subgraph(G,shortestpath(G,3,21));
Gpath{7} = subgraph(G,shortestpath(G,17,12));
Gpath{8} = subgraph(G,shortestpath(G,17,23));
Gpath{9} = subgraph(G,shortestpath(G,17,26));
% Figure
hold on
p(1) = plot(G,’XData’,G.Nodes.X,’YData’,G.Nodes.Y,’LineWidth’,1,’EdgeColor’,’k’,’NodeColor’,’k’);
for i = [1 2 3]
p(2) = plot(Gpath{i},’XData’,Gpath{i}.Nodes.X,’YData’,Gpath{i}.Nodes.Y,’EdgeColor’,’y’,’NodeColor’,’y’);
p(2).NodeLabel = {};
p(2).EdgeAlpha = 1;
p(2).LineWidth = 5;
end
for i = [7 8 9]
p(3) = plot(Gpath{i},’XData’,Gpath{i}.Nodes.X,’YData’,Gpath{i}.Nodes.Y,’EdgeColor’,’g’,’NodeColor’,’g’);
p(3).NodeLabel = {};
p(3).EdgeAlpha = 1;
p(3).LineWidth = 9;
p(3).DisplayName = ‘Apple’;
end
for i = [4 5 6]
p(4) = plot(Gpath{i},’XData’,Gpath{i}.Nodes.X,’YData’,Gpath{i}.Nodes.Y,’EdgeColor’,’r’,’NodeColor’,’r’);
p(4).NodeLabel = {};
p(4).EdgeAlpha = 1;
p(4).LineWidth = 15;
p(4).DisplayName = ‘Strawberry’;
end
legend(p)
Just for clarity and a better understanding, here below I plot the GraphPlots separately as well:
Problem. When I try the to use uistack to change the visual stacking of the 4 GraphPlots, by bringing to the bottom both the GraphPlots called "Apple" (in green) and "Strawberry" (in red),
% Select the GraphPlots which have a non-empty "DisplayName", i.e. "Apple"
% and "Strawberry", and use Uistack
idx = find(~cellfun(@isempty,{p.DisplayName}));
p2 = uistack(p(idx),’bottom’)
legend(p2)
Only some Subgraphs are reshuffled, which means, to the best of my understanding, that uistack does not act on the 4 GraphPlots of "p", but, instead, on the 10 GraphPlots of "p2", i.e on the single Subgraphs:
Question. How to get what I expect, i.e. the following plot, where the 4 GraphPlots of "p" are reshuffled:
Note. Also, I have noticed that "p" and the "uistacked p", i.e. "p2", have different dimensions, and I guess it is the source of the problem:
p =
1×4 GraphPlot array:
GraphPlot GraphPlot GraphPlot GraphPlot
p2 =
10×1 GraphPlot array:
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot Introduction. I have the following Graph and Subgraphs:
% Graph
s = [1 1 1 3 3 6 7 8 9 10 4 12 13 5 15 16 17 18 19 19 20 20 17 24 25 4 27 28 29];
t = [2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30];
G = graph(s,t);
% Node ID: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
G.Nodes.X = [2 1 3 2 4 4 5 4 5 4 5 1 3 3 5 6 7 6 8 7 9 8 9 8 9 10 1 1 0 1]’;
G.Nodes.Y = [2 1 3 9 3 5 8 12 13 18 21 15 18 21 0 2 8 12 15 20 10 22 18 5 4 4 5 8 12 23]’;
% Subgraphs
Gpath{1} = subgraph(G,shortestpath(G,4,14));
Gpath{2} = subgraph(G,shortestpath(G,4,26));
Gpath{3} = subgraph(G,shortestpath(G,4,30));
Gpath{4} = subgraph(G,shortestpath(G,3,10));
Gpath{5} = subgraph(G,shortestpath(G,3,28));
Gpath{6} = subgraph(G,shortestpath(G,3,21));
Gpath{7} = subgraph(G,shortestpath(G,17,12));
Gpath{8} = subgraph(G,shortestpath(G,17,23));
Gpath{9} = subgraph(G,shortestpath(G,17,26));
% Figure
hold on
p(1) = plot(G,’XData’,G.Nodes.X,’YData’,G.Nodes.Y,’LineWidth’,1,’EdgeColor’,’k’,’NodeColor’,’k’);
for i = [1 2 3]
p(2) = plot(Gpath{i},’XData’,Gpath{i}.Nodes.X,’YData’,Gpath{i}.Nodes.Y,’EdgeColor’,’y’,’NodeColor’,’y’);
p(2).NodeLabel = {};
p(2).EdgeAlpha = 1;
p(2).LineWidth = 5;
end
for i = [7 8 9]
p(3) = plot(Gpath{i},’XData’,Gpath{i}.Nodes.X,’YData’,Gpath{i}.Nodes.Y,’EdgeColor’,’g’,’NodeColor’,’g’);
p(3).NodeLabel = {};
p(3).EdgeAlpha = 1;
p(3).LineWidth = 9;
p(3).DisplayName = ‘Apple’;
end
for i = [4 5 6]
p(4) = plot(Gpath{i},’XData’,Gpath{i}.Nodes.X,’YData’,Gpath{i}.Nodes.Y,’EdgeColor’,’r’,’NodeColor’,’r’);
p(4).NodeLabel = {};
p(4).EdgeAlpha = 1;
p(4).LineWidth = 15;
p(4).DisplayName = ‘Strawberry’;
end
legend(p)
Just for clarity and a better understanding, here below I plot the GraphPlots separately as well:
Problem. When I try the to use uistack to change the visual stacking of the 4 GraphPlots, by bringing to the bottom both the GraphPlots called "Apple" (in green) and "Strawberry" (in red),
% Select the GraphPlots which have a non-empty "DisplayName", i.e. "Apple"
% and "Strawberry", and use Uistack
idx = find(~cellfun(@isempty,{p.DisplayName}));
p2 = uistack(p(idx),’bottom’)
legend(p2)
Only some Subgraphs are reshuffled, which means, to the best of my understanding, that uistack does not act on the 4 GraphPlots of "p", but, instead, on the 10 GraphPlots of "p2", i.e on the single Subgraphs:
Question. How to get what I expect, i.e. the following plot, where the 4 GraphPlots of "p" are reshuffled:
Note. Also, I have noticed that "p" and the "uistacked p", i.e. "p2", have different dimensions, and I guess it is the source of the problem:
p =
1×4 GraphPlot array:
GraphPlot GraphPlot GraphPlot GraphPlot
p2 =
10×1 GraphPlot array:
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot
GraphPlot uistack, graph, subgraph, graphplot, visual stack MATLAB Answers — New Questions
Phase retrieval of a periodic signal, not working well
Hello,
I am trying solve something I thought would be straigfoward, but is not so far ^^.
Let assume we have a perriodic signal as such:
x=0:400;
T=39.5;
PhiO=0.43;
y=5+cos((2*pi/T).*x+PhiO);
And the aim is to get the phase and period of this signal.
Here is for the code for the period retriaval:
%period
[pks,locs] = findpeaks(y,’MinPeakDistance’,20) ;
Px_av=mean(diff(locs));
Here is the code for the phase retrieval:
h=fft(y);
plot(abs(h)) % the eleventh element is the frequency of my signal so the eleventh element of the phase "angle(h)" should be the phase of my signal. But if I plot the original signal and the retrieved one, it doesn’t match well:
Phi=angle(h);
plot(x,max(y).*cos((2*pi/Px_av).*x+Phi(1,11)));hold on;plot(x,y)
Given that PhiO and Px_av are different, I tried to use interp Phi to match the right frequency, but it doesn’t work either.
Do you understand what I do wrong, please ?Hello,
I am trying solve something I thought would be straigfoward, but is not so far ^^.
Let assume we have a perriodic signal as such:
x=0:400;
T=39.5;
PhiO=0.43;
y=5+cos((2*pi/T).*x+PhiO);
And the aim is to get the phase and period of this signal.
Here is for the code for the period retriaval:
%period
[pks,locs] = findpeaks(y,’MinPeakDistance’,20) ;
Px_av=mean(diff(locs));
Here is the code for the phase retrieval:
h=fft(y);
plot(abs(h)) % the eleventh element is the frequency of my signal so the eleventh element of the phase "angle(h)" should be the phase of my signal. But if I plot the original signal and the retrieved one, it doesn’t match well:
Phi=angle(h);
plot(x,max(y).*cos((2*pi/Px_av).*x+Phi(1,11)));hold on;plot(x,y)
Given that PhiO and Px_av are different, I tried to use interp Phi to match the right frequency, but it doesn’t work either.
Do you understand what I do wrong, please ? Hello,
I am trying solve something I thought would be straigfoward, but is not so far ^^.
Let assume we have a perriodic signal as such:
x=0:400;
T=39.5;
PhiO=0.43;
y=5+cos((2*pi/T).*x+PhiO);
And the aim is to get the phase and period of this signal.
Here is for the code for the period retriaval:
%period
[pks,locs] = findpeaks(y,’MinPeakDistance’,20) ;
Px_av=mean(diff(locs));
Here is the code for the phase retrieval:
h=fft(y);
plot(abs(h)) % the eleventh element is the frequency of my signal so the eleventh element of the phase "angle(h)" should be the phase of my signal. But if I plot the original signal and the retrieved one, it doesn’t match well:
Phi=angle(h);
plot(x,max(y).*cos((2*pi/Px_av).*x+Phi(1,11)));hold on;plot(x,y)
Given that PhiO and Px_av are different, I tried to use interp Phi to match the right frequency, but it doesn’t work either.
Do you understand what I do wrong, please ? phase retrieval, matlab, fft MATLAB Answers — New Questions
Genetic algorithm constraint definition
Dear All,
I am currently working on a project involving a genetic algorithm. The project focuses on optimizing a circular structure, where the variables under consideration are the strut radius (tr) and the fillet radius (fr). The genetic algorithm selects these variables, and based on the chosen values, a subroutine is invoked to generate the structure. Subsequently, a finite element analysis (FEA) is conducted using a PDE solver. From this analysis, stress and relative density values are exported.
The objective of my optimization is to minimize stress while maintaining a relative density below 0.2. For example, I have defined a population size of 10. The genetic algorithm selects different values for the design variables; however, the 11th population set is identical to the 1st, leading to an error stating "Optimization finished: no feasible point found."
I believe the issue lies in the constraint definition or the linkage between the objective function and the constraint function.
Thank you for your time and assistance.
Best regards,
Here is some lines of my code,
% Clean up
clear all; close all; clc;
tic
% Set up optimization options
format long
options = gaoptimset(‘OutputFcn’,@SaveOut,…
‘Display’, ‘iter’,…
‘PopulationSize’, 10,…
‘Generations’, 10,…
‘EliteCount’, 2,…
‘CrossoverFraction’, 0.95,…
‘TolFun’, 1.0e-9,…
‘TolCon’, 1.0e-9,…
‘StallTimeLimit’, Inf,…
‘FitnessLimit’, -Inf,…
‘PlotFcn’,{@gaplotbestf,@gaplotstopping});
% Define variables and bounds
nvars = 2; % Strut radius: tr and Fillet radius: fr
LB = [1, 0]; % Lower bounds for tr and fr
UB = [5, 5]; % Upper bounds for tr and fr
X0 = [1 0]; % Start point
options.InitialPopulationMatrix = X0;
% Define objective function and constraints
ObjectiveFunction = @(x) simple_objective(x);
nonlcon = @(x) simple_const(x);
% Call ga
[x,fval,output,population,exitflag] = ga(ObjectiveFunction,nvars,…
[],[],[],[],LB,UB,nonlcon,[],options);
toc
%% Objective Function
function cost = simple_objective(x)
% Generate new structure
tr = x(1); % strut radius
fr = x(2); % fillet radius
a = 10; % unit cell size
BCC_stl_generator(a, tr, fr);
% RUN FEA
FEA_ANALYSIS(tr); % Then, export results to a text file FEA_Results.txt
% Read results
fileID = fopen(‘FEA_Results.txt’, ‘r’);
results = fscanf(fileID,’%f’,[1,inf]);
fclose(fileID);
MaxVonMisesStress = results(1);
RelativeDensity = results(2);
cost = MaxVonMisesStress; % Objective is to minimize MaxVonMisesStress
end
%% Constraint Function
function [c, ceq] = simple_const(x)
fileID = fopen(‘FEA_Results.txt’, ‘r’);
results = fscanf(fileID,’%f’,[1,inf]);
fclose(fileID);
MaxVonMisesStress = results(1);
RelativeDensity = results(2);
tol=0.001;
c = RelativeDensity – 0.2 – tol; % Constraint: RelativeDensity must be <= 0.2
% The minimum and maximum relative density values are 0.116 and 0.494, rescpectively.
ceq = [];
endDear All,
I am currently working on a project involving a genetic algorithm. The project focuses on optimizing a circular structure, where the variables under consideration are the strut radius (tr) and the fillet radius (fr). The genetic algorithm selects these variables, and based on the chosen values, a subroutine is invoked to generate the structure. Subsequently, a finite element analysis (FEA) is conducted using a PDE solver. From this analysis, stress and relative density values are exported.
The objective of my optimization is to minimize stress while maintaining a relative density below 0.2. For example, I have defined a population size of 10. The genetic algorithm selects different values for the design variables; however, the 11th population set is identical to the 1st, leading to an error stating "Optimization finished: no feasible point found."
I believe the issue lies in the constraint definition or the linkage between the objective function and the constraint function.
Thank you for your time and assistance.
Best regards,
Here is some lines of my code,
% Clean up
clear all; close all; clc;
tic
% Set up optimization options
format long
options = gaoptimset(‘OutputFcn’,@SaveOut,…
‘Display’, ‘iter’,…
‘PopulationSize’, 10,…
‘Generations’, 10,…
‘EliteCount’, 2,…
‘CrossoverFraction’, 0.95,…
‘TolFun’, 1.0e-9,…
‘TolCon’, 1.0e-9,…
‘StallTimeLimit’, Inf,…
‘FitnessLimit’, -Inf,…
‘PlotFcn’,{@gaplotbestf,@gaplotstopping});
% Define variables and bounds
nvars = 2; % Strut radius: tr and Fillet radius: fr
LB = [1, 0]; % Lower bounds for tr and fr
UB = [5, 5]; % Upper bounds for tr and fr
X0 = [1 0]; % Start point
options.InitialPopulationMatrix = X0;
% Define objective function and constraints
ObjectiveFunction = @(x) simple_objective(x);
nonlcon = @(x) simple_const(x);
% Call ga
[x,fval,output,population,exitflag] = ga(ObjectiveFunction,nvars,…
[],[],[],[],LB,UB,nonlcon,[],options);
toc
%% Objective Function
function cost = simple_objective(x)
% Generate new structure
tr = x(1); % strut radius
fr = x(2); % fillet radius
a = 10; % unit cell size
BCC_stl_generator(a, tr, fr);
% RUN FEA
FEA_ANALYSIS(tr); % Then, export results to a text file FEA_Results.txt
% Read results
fileID = fopen(‘FEA_Results.txt’, ‘r’);
results = fscanf(fileID,’%f’,[1,inf]);
fclose(fileID);
MaxVonMisesStress = results(1);
RelativeDensity = results(2);
cost = MaxVonMisesStress; % Objective is to minimize MaxVonMisesStress
end
%% Constraint Function
function [c, ceq] = simple_const(x)
fileID = fopen(‘FEA_Results.txt’, ‘r’);
results = fscanf(fileID,’%f’,[1,inf]);
fclose(fileID);
MaxVonMisesStress = results(1);
RelativeDensity = results(2);
tol=0.001;
c = RelativeDensity – 0.2 – tol; % Constraint: RelativeDensity must be <= 0.2
% The minimum and maximum relative density values are 0.116 and 0.494, rescpectively.
ceq = [];
end Dear All,
I am currently working on a project involving a genetic algorithm. The project focuses on optimizing a circular structure, where the variables under consideration are the strut radius (tr) and the fillet radius (fr). The genetic algorithm selects these variables, and based on the chosen values, a subroutine is invoked to generate the structure. Subsequently, a finite element analysis (FEA) is conducted using a PDE solver. From this analysis, stress and relative density values are exported.
The objective of my optimization is to minimize stress while maintaining a relative density below 0.2. For example, I have defined a population size of 10. The genetic algorithm selects different values for the design variables; however, the 11th population set is identical to the 1st, leading to an error stating "Optimization finished: no feasible point found."
I believe the issue lies in the constraint definition or the linkage between the objective function and the constraint function.
Thank you for your time and assistance.
Best regards,
Here is some lines of my code,
% Clean up
clear all; close all; clc;
tic
% Set up optimization options
format long
options = gaoptimset(‘OutputFcn’,@SaveOut,…
‘Display’, ‘iter’,…
‘PopulationSize’, 10,…
‘Generations’, 10,…
‘EliteCount’, 2,…
‘CrossoverFraction’, 0.95,…
‘TolFun’, 1.0e-9,…
‘TolCon’, 1.0e-9,…
‘StallTimeLimit’, Inf,…
‘FitnessLimit’, -Inf,…
‘PlotFcn’,{@gaplotbestf,@gaplotstopping});
% Define variables and bounds
nvars = 2; % Strut radius: tr and Fillet radius: fr
LB = [1, 0]; % Lower bounds for tr and fr
UB = [5, 5]; % Upper bounds for tr and fr
X0 = [1 0]; % Start point
options.InitialPopulationMatrix = X0;
% Define objective function and constraints
ObjectiveFunction = @(x) simple_objective(x);
nonlcon = @(x) simple_const(x);
% Call ga
[x,fval,output,population,exitflag] = ga(ObjectiveFunction,nvars,…
[],[],[],[],LB,UB,nonlcon,[],options);
toc
%% Objective Function
function cost = simple_objective(x)
% Generate new structure
tr = x(1); % strut radius
fr = x(2); % fillet radius
a = 10; % unit cell size
BCC_stl_generator(a, tr, fr);
% RUN FEA
FEA_ANALYSIS(tr); % Then, export results to a text file FEA_Results.txt
% Read results
fileID = fopen(‘FEA_Results.txt’, ‘r’);
results = fscanf(fileID,’%f’,[1,inf]);
fclose(fileID);
MaxVonMisesStress = results(1);
RelativeDensity = results(2);
cost = MaxVonMisesStress; % Objective is to minimize MaxVonMisesStress
end
%% Constraint Function
function [c, ceq] = simple_const(x)
fileID = fopen(‘FEA_Results.txt’, ‘r’);
results = fscanf(fileID,’%f’,[1,inf]);
fclose(fileID);
MaxVonMisesStress = results(1);
RelativeDensity = results(2);
tol=0.001;
c = RelativeDensity – 0.2 – tol; % Constraint: RelativeDensity must be <= 0.2
% The minimum and maximum relative density values are 0.116 and 0.494, rescpectively.
ceq = [];
end genetic algorithm MATLAB Answers — New Questions
After running the Python program in Matlab, the parquetread function cannot be used
The parquetread function runs smoothly without running Python programs in Matlab.
But when matlab runs the Python program, the parquetread function cannot be used. The error is as follows:
Caught "std:: exception" Exception message is:
Loading D: Program MATLAB R2021a bin win64 builtins matlab_toolbox_parque mwlibmwparque builtinimpl. dllfailed with error: The specified program cannot be found.
: state not recoverable: state not recoverable
I use
Matlab2021a version
Python 3.8 version
How can I solve it? Thank you.The parquetread function runs smoothly without running Python programs in Matlab.
But when matlab runs the Python program, the parquetread function cannot be used. The error is as follows:
Caught "std:: exception" Exception message is:
Loading D: Program MATLAB R2021a bin win64 builtins matlab_toolbox_parque mwlibmwparque builtinimpl. dllfailed with error: The specified program cannot be found.
: state not recoverable: state not recoverable
I use
Matlab2021a version
Python 3.8 version
How can I solve it? Thank you. The parquetread function runs smoothly without running Python programs in Matlab.
But when matlab runs the Python program, the parquetread function cannot be used. The error is as follows:
Caught "std:: exception" Exception message is:
Loading D: Program MATLAB R2021a bin win64 builtins matlab_toolbox_parque mwlibmwparque builtinimpl. dllfailed with error: The specified program cannot be found.
: state not recoverable: state not recoverable
I use
Matlab2021a version
Python 3.8 version
How can I solve it? Thank you. python, parquet, wrong MATLAB Answers — New Questions
Help with ocean transect plot
Hi Matlabbers,
I’m fairly new to the community and struggling to make a transect plot of some nitrate data that I have from CTD casts. I have 11 stations across an area, each with different depths, and each with various nitrate concentration data.
So, what I want to produce is a transect plot, showing water depth on the y axis, distance between stations on x-axis and the nitrate concentration at each station on the z-axis, but in a 2D plot.
My issue is, for each station, the depth varies, and my nitrate concentration data is quite scattered, hence I want to interpolate it so that for missing data (NaNs), it takes the concentration from neighbouring stations at the same depth and generates a value. When I do this using my data, Matlab interpolates across the rows which doesnt work since there are various depths across each row. I can’t really make a uniform depth profile because it differs so much between each station. I’ve tried fillmissing and interp1 to get around the fact that i have so many NaN values, but the results are really blocky.
Any suggestions?
This is what I currently get:
And this is the sort of look I’m after
Thanks in advance :)Hi Matlabbers,
I’m fairly new to the community and struggling to make a transect plot of some nitrate data that I have from CTD casts. I have 11 stations across an area, each with different depths, and each with various nitrate concentration data.
So, what I want to produce is a transect plot, showing water depth on the y axis, distance between stations on x-axis and the nitrate concentration at each station on the z-axis, but in a 2D plot.
My issue is, for each station, the depth varies, and my nitrate concentration data is quite scattered, hence I want to interpolate it so that for missing data (NaNs), it takes the concentration from neighbouring stations at the same depth and generates a value. When I do this using my data, Matlab interpolates across the rows which doesnt work since there are various depths across each row. I can’t really make a uniform depth profile because it differs so much between each station. I’ve tried fillmissing and interp1 to get around the fact that i have so many NaN values, but the results are really blocky.
Any suggestions?
This is what I currently get:
And this is the sort of look I’m after
Thanks in advance 🙂 Hi Matlabbers,
I’m fairly new to the community and struggling to make a transect plot of some nitrate data that I have from CTD casts. I have 11 stations across an area, each with different depths, and each with various nitrate concentration data.
So, what I want to produce is a transect plot, showing water depth on the y axis, distance between stations on x-axis and the nitrate concentration at each station on the z-axis, but in a 2D plot.
My issue is, for each station, the depth varies, and my nitrate concentration data is quite scattered, hence I want to interpolate it so that for missing data (NaNs), it takes the concentration from neighbouring stations at the same depth and generates a value. When I do this using my data, Matlab interpolates across the rows which doesnt work since there are various depths across each row. I can’t really make a uniform depth profile because it differs so much between each station. I’ve tried fillmissing and interp1 to get around the fact that i have so many NaN values, but the results are really blocky.
Any suggestions?
This is what I currently get:
And this is the sort of look I’m after
Thanks in advance 🙂 interpolation, plotting, scattered data, transect plot MATLAB Answers — New Questions
need know program of arduino mega 2560
i have an old arduino mega2560 board, i want to change some parameter, but i am unable open file from this arduino , can someone help me.i have an old arduino mega2560 board, i want to change some parameter, but i am unable open file from this arduino , can someone help me. i have an old arduino mega2560 board, i want to change some parameter, but i am unable open file from this arduino , can someone help me. arduino mega2560 MATLAB Answers — New Questions
Why does the pressure diverge so quickly, and what is the solution?
clc; % Clear the command window
clear; % Clear all variables
% Input parameters
rho_fluid = 1220;
rho_copper = 8960; % Density of copper in kg/m^3
L_X = 0.0043;
L_Y = 0.0001;
L_Z = 0.0002;
n_X = 300;
n_Y = 50;
n_Z = 50;
u_inlet = 0.05; % Reduced inlet velocity in m/s
nu = 1e-6; % Kinematic viscosity of the fluid (m^2/s)
tolerance = 1e-6; % Convergence tolerance
max_iter = 10000; % Maximum number of iterations
dt = 1e-10; % Further reduced time step for better numerical stability
% Calculate delta
delta_x = L_X / (n_X – 1); % Grid spacing in X direction
delta_y = L_Y / (n_Y – 1); % Grid spacing in Y direction
delta_z = L_Z / (n_Z – 1); % Grid spacing in Z direction
% Define pin positions and dimensions
pin_radius = 0.0001; % Radius of the pins
pin_height = L_Z; % Height of the pins (same as channel height)
pin_positions = [0.001 0.00005; 0.002 0.00005; 0.003 0.00005; 0.0015 0.00005; 0.0025 0.00005]; % X and Y coordinates of pin centers
% Identify grid points inside and on the surface of pins
is_pin = false(n_X, n_Y, n_Z);
is_surface_pin = false(n_X, n_Y, n_Z);
for p = 1:size(pin_positions, 1)
for i = 1:n_X
for j = 1:n_Y
for k = 1:n_Z
x = (i-1) * delta_x;
y = (j-1) * delta_y;
distance = sqrt((x – pin_positions(p, 1))^2 + (y – pin_positions(p, 2))^2);
if distance <= pin_radius
is_pin(i, j, k) = true;
end
if abs(distance – pin_radius) < (delta_x / 2) % Near the surface
is_surface_pin(i, j, k) = true;
end
end
end
end
end
% Initialize velocity and pressure fields
u = zeros(n_X, n_Y, n_Z); % Initialize with zeros to avoid initial instability
v = zeros(n_X, n_Y, n_Z);
w = zeros(n_X, n_Y, n_Z);
p = zeros(n_X, n_Y, n_Z);
% Time-stepping method for solving Navier-Stokes equations using ADI method
for iter = 1:max_iter
u_old = u;
v_old = v;
w_old = w;
p_old = p;
% Solve for velocity fields (x-direction)
for j = 2:n_Y-1
for k = 2:n_Z-1
for i = 2:n_X-1
if ~is_pin(i, j, k)
% x-momentum equation (ADI method)
u(i,j,k) = u_old(i,j,k) + dt/2 * ( …
– u_old(i,j,k) * (u_old(i+1,j,k) – u_old(i-1,j,k)) / (2 * delta_x) …
– v_old(i,j,k) * (u_old(i,j+1,k) – u_old(i,j-1,k)) / (2 * delta_y) …
– w_old(i,j,k) * (u_old(i,j,k+1) – u_old(i,j,k-1)) / (2 * delta_z) …
+ (p_old(i+1,j,k) – p_old(i-1,j,k)) / (2 * delta_x * rho_fluid) …
+ nu * ((u_old(i+1,j,k) – 2*u_old(i,j,k) + u_old(i-1,j,k)) / delta_x^2 …
+ (u_old(i,j+1,k) – 2*u_old(i,j,k) + u_old(i,j-1,k)) / delta_y^2 …
+ (u_old(i,j,k+1) – 2*u_old(i,j,k) + u_old(i,j,k-1)) / delta_z^2) …
);
end
end
end
end
% Solve for velocity fields (y-direction)
for i = 2:n_X-1
for k = 2:n_Z-1
for j = 2:n_Y-1
if ~is_pin(i, j, k)
% y-momentum equation (ADI method)
v(i,j,k) = v_old(i,j,k) + dt/2 * ( …
– u_old(i,j,k) * (v_old(i+1,j,k) – v_old(i-1,j,k)) / (2 * delta_x) …
– v_old(i,j,k) * (v_old(i,j+1,k) – v_old(i,j-1,k)) / (2 * delta_y) …
– w_old(i,j,k) * (v_old(i,j,k+1) – v_old(i,j,k-1)) / (2 * delta_z) …
+ (p_old(i,j+1,k) – p_old(i,j-1,k)) / (2 * delta_y * rho_fluid) …
+ nu * ((v_old(i+1,j,k) – 2*v_old(i,j,k) + v_old(i-1,j,k)) / delta_x^2 …
+ (v_old(i,j+1,k) – 2*v_old(i,j,k) + v_old(i,j-1,k)) / delta_y^2 …
+ (v_old(i,j,k+1) – 2*v_old(i,j,k) + v_old(i,j,k-1)) / delta_z^2) …
);
end
end
end
end
% Solve for velocity fields (z-direction)
for i = 2:n_X-1
for j = 2:n_Y-1
for k = 2:n_Z-1
if ~is_pin(i, j, k)
% z-momentum equation (ADI method)
w(i,j,k) = w_old(i,j,k) + dt/2 * ( …
– u_old(i,j,k) * (w_old(i+1,j,k) – w_old(i-1,j,k)) / (2 * delta_x) …
– v_old(i,j,k) * (w_old(i,j+1,k) – w_old(i,j-1,k)) / (2 * delta_y) …
– w_old(i,j,k) * (w_old(i,j,k+1) – w_old(i,j,k-1)) / (2 * delta_z) …
+ (p_old(i,j,k+1) – p_old(i,j,k-1)) / (2 * delta_z * rho_fluid) …
+ nu * ((w_old(i+1,j,k) – 2*w_old(i,j,k) + w_old(i-1,j,k)) / delta_x^2 …
+ (w_old(i,j+1,k) – 2*w_old(i,j,k) + w_old(i,j-1,k)) / delta_y^2 …
+ (w_old(i,j,k+1) – 2*w_old(i,j,k) + w_old(i,j,k-1)) / delta_z^2) …
);
end
end
end
end
% Solve for pressure field using the pressure Poisson equation
for i = 2:n_X-1
for j = 2:n_Y-1
for k = 2:n_Z-1
if ~is_pin(i, j, k)
p(i,j,k) = (p_old(i+1,j,k) + p_old(i-1,j,k) + p_old(i,j+1,k) + p_old(i,j-1,k) + p_old(i,j,k+1) + p_old(i,j,k-1)) / 6 …
– (rho_fluid / 6) * ((u(i+1,j,k) – u(i-1,j,k)) / (2 * delta_x) …
+ (v(i,j+1,k) – v(i,j-1,k)) / (2 * delta_y) …
+ (w(i,j,k+1) – w(i,j,k-1)) / (2 * delta_z));
end
end
end
end
% Inlet boundary condition for velocity
u(1, :, 🙂 = u_inlet;
% Outlet boundary condition for pressure
p(n_X, :, 🙂 = 0; % Assume atmospheric pressure at the outlet
% No-slip boundary conditions for velocity at the walls and pins
u(:, :, 1) = 0; % Bottom wall
u(:, :, n_Z) = 0; % Top wall
u(is_pin) = 0; % Surface of pins
v(:, :, 1) = 0; % Bottom wall
v(:, :, n_Z) = 0; % Top wall
v(is_pin) = 0; % Surface of pins
w(:, :, 1) = 0; % Bottom wall
w(:, :, n_Z) = 0; % Top wall
w(is_pin) = 0; % Surface of pins
% Symmetry boundary conditions for velocity at the side walls
u(:, 1, 🙂 = u(:, 2, :); % Left side wall
u(:, n_Y, 🙂 = u(:, n_Y-1, :); % Right side wall
v(:, 1, 🙂 = v(:, 2, :); % Left side wall
v(:, n_Y, 🙂 = v(:, n_Y-1, :); % Right side wall
w(:, 1, 🙂 = w(:, 2, :); % Left side wall
w(:, n_Y, 🙂 = w(:, n_Y-1, :); % Right side wall
% Convergence check
max_diff_u = max(max(max(abs(u – u_old))));
max_diff_v = max(max(max(abs(v – v_old))));
max_diff_w = max(max(max(abs(w – w_old))));
max_diff_p = max(max(max(abs(p – p_old))));
disp([‘Max difference in u: ‘, num2str(max_diff_u)]);
disp([‘Max difference in v: ‘, num2str(max_diff_v)]);
disp([‘Max difference in w: ‘, num2str(max_diff_w)]);
disp([‘Max difference in p: ‘, num2str(max_diff_p)]);
if max_diff_u < tolerance && max_diff_v < tolerance && max_diff_w < tolerance && max_diff_p < tolerance
disp(‘Converged’);
break; % Exit the loop if converged
end
% Check for NaN or Inf values
if any(isnan(u(:))) || any(isinf(u(:))) || any(isnan(v(:))) || any(isinf(v(:))) || any(isnan(w(:))) || any(isinf(w(:))) || any(isnan(p(:))) || any(isinf(p(:)))
disp(‘Error: NaN or Inf detected in velocity or pressure matrix’);
break;
end
endclc; % Clear the command window
clear; % Clear all variables
% Input parameters
rho_fluid = 1220;
rho_copper = 8960; % Density of copper in kg/m^3
L_X = 0.0043;
L_Y = 0.0001;
L_Z = 0.0002;
n_X = 300;
n_Y = 50;
n_Z = 50;
u_inlet = 0.05; % Reduced inlet velocity in m/s
nu = 1e-6; % Kinematic viscosity of the fluid (m^2/s)
tolerance = 1e-6; % Convergence tolerance
max_iter = 10000; % Maximum number of iterations
dt = 1e-10; % Further reduced time step for better numerical stability
% Calculate delta
delta_x = L_X / (n_X – 1); % Grid spacing in X direction
delta_y = L_Y / (n_Y – 1); % Grid spacing in Y direction
delta_z = L_Z / (n_Z – 1); % Grid spacing in Z direction
% Define pin positions and dimensions
pin_radius = 0.0001; % Radius of the pins
pin_height = L_Z; % Height of the pins (same as channel height)
pin_positions = [0.001 0.00005; 0.002 0.00005; 0.003 0.00005; 0.0015 0.00005; 0.0025 0.00005]; % X and Y coordinates of pin centers
% Identify grid points inside and on the surface of pins
is_pin = false(n_X, n_Y, n_Z);
is_surface_pin = false(n_X, n_Y, n_Z);
for p = 1:size(pin_positions, 1)
for i = 1:n_X
for j = 1:n_Y
for k = 1:n_Z
x = (i-1) * delta_x;
y = (j-1) * delta_y;
distance = sqrt((x – pin_positions(p, 1))^2 + (y – pin_positions(p, 2))^2);
if distance <= pin_radius
is_pin(i, j, k) = true;
end
if abs(distance – pin_radius) < (delta_x / 2) % Near the surface
is_surface_pin(i, j, k) = true;
end
end
end
end
end
% Initialize velocity and pressure fields
u = zeros(n_X, n_Y, n_Z); % Initialize with zeros to avoid initial instability
v = zeros(n_X, n_Y, n_Z);
w = zeros(n_X, n_Y, n_Z);
p = zeros(n_X, n_Y, n_Z);
% Time-stepping method for solving Navier-Stokes equations using ADI method
for iter = 1:max_iter
u_old = u;
v_old = v;
w_old = w;
p_old = p;
% Solve for velocity fields (x-direction)
for j = 2:n_Y-1
for k = 2:n_Z-1
for i = 2:n_X-1
if ~is_pin(i, j, k)
% x-momentum equation (ADI method)
u(i,j,k) = u_old(i,j,k) + dt/2 * ( …
– u_old(i,j,k) * (u_old(i+1,j,k) – u_old(i-1,j,k)) / (2 * delta_x) …
– v_old(i,j,k) * (u_old(i,j+1,k) – u_old(i,j-1,k)) / (2 * delta_y) …
– w_old(i,j,k) * (u_old(i,j,k+1) – u_old(i,j,k-1)) / (2 * delta_z) …
+ (p_old(i+1,j,k) – p_old(i-1,j,k)) / (2 * delta_x * rho_fluid) …
+ nu * ((u_old(i+1,j,k) – 2*u_old(i,j,k) + u_old(i-1,j,k)) / delta_x^2 …
+ (u_old(i,j+1,k) – 2*u_old(i,j,k) + u_old(i,j-1,k)) / delta_y^2 …
+ (u_old(i,j,k+1) – 2*u_old(i,j,k) + u_old(i,j,k-1)) / delta_z^2) …
);
end
end
end
end
% Solve for velocity fields (y-direction)
for i = 2:n_X-1
for k = 2:n_Z-1
for j = 2:n_Y-1
if ~is_pin(i, j, k)
% y-momentum equation (ADI method)
v(i,j,k) = v_old(i,j,k) + dt/2 * ( …
– u_old(i,j,k) * (v_old(i+1,j,k) – v_old(i-1,j,k)) / (2 * delta_x) …
– v_old(i,j,k) * (v_old(i,j+1,k) – v_old(i,j-1,k)) / (2 * delta_y) …
– w_old(i,j,k) * (v_old(i,j,k+1) – v_old(i,j,k-1)) / (2 * delta_z) …
+ (p_old(i,j+1,k) – p_old(i,j-1,k)) / (2 * delta_y * rho_fluid) …
+ nu * ((v_old(i+1,j,k) – 2*v_old(i,j,k) + v_old(i-1,j,k)) / delta_x^2 …
+ (v_old(i,j+1,k) – 2*v_old(i,j,k) + v_old(i,j-1,k)) / delta_y^2 …
+ (v_old(i,j,k+1) – 2*v_old(i,j,k) + v_old(i,j,k-1)) / delta_z^2) …
);
end
end
end
end
% Solve for velocity fields (z-direction)
for i = 2:n_X-1
for j = 2:n_Y-1
for k = 2:n_Z-1
if ~is_pin(i, j, k)
% z-momentum equation (ADI method)
w(i,j,k) = w_old(i,j,k) + dt/2 * ( …
– u_old(i,j,k) * (w_old(i+1,j,k) – w_old(i-1,j,k)) / (2 * delta_x) …
– v_old(i,j,k) * (w_old(i,j+1,k) – w_old(i,j-1,k)) / (2 * delta_y) …
– w_old(i,j,k) * (w_old(i,j,k+1) – w_old(i,j,k-1)) / (2 * delta_z) …
+ (p_old(i,j,k+1) – p_old(i,j,k-1)) / (2 * delta_z * rho_fluid) …
+ nu * ((w_old(i+1,j,k) – 2*w_old(i,j,k) + w_old(i-1,j,k)) / delta_x^2 …
+ (w_old(i,j+1,k) – 2*w_old(i,j,k) + w_old(i,j-1,k)) / delta_y^2 …
+ (w_old(i,j,k+1) – 2*w_old(i,j,k) + w_old(i,j,k-1)) / delta_z^2) …
);
end
end
end
end
% Solve for pressure field using the pressure Poisson equation
for i = 2:n_X-1
for j = 2:n_Y-1
for k = 2:n_Z-1
if ~is_pin(i, j, k)
p(i,j,k) = (p_old(i+1,j,k) + p_old(i-1,j,k) + p_old(i,j+1,k) + p_old(i,j-1,k) + p_old(i,j,k+1) + p_old(i,j,k-1)) / 6 …
– (rho_fluid / 6) * ((u(i+1,j,k) – u(i-1,j,k)) / (2 * delta_x) …
+ (v(i,j+1,k) – v(i,j-1,k)) / (2 * delta_y) …
+ (w(i,j,k+1) – w(i,j,k-1)) / (2 * delta_z));
end
end
end
end
% Inlet boundary condition for velocity
u(1, :, 🙂 = u_inlet;
% Outlet boundary condition for pressure
p(n_X, :, 🙂 = 0; % Assume atmospheric pressure at the outlet
% No-slip boundary conditions for velocity at the walls and pins
u(:, :, 1) = 0; % Bottom wall
u(:, :, n_Z) = 0; % Top wall
u(is_pin) = 0; % Surface of pins
v(:, :, 1) = 0; % Bottom wall
v(:, :, n_Z) = 0; % Top wall
v(is_pin) = 0; % Surface of pins
w(:, :, 1) = 0; % Bottom wall
w(:, :, n_Z) = 0; % Top wall
w(is_pin) = 0; % Surface of pins
% Symmetry boundary conditions for velocity at the side walls
u(:, 1, 🙂 = u(:, 2, :); % Left side wall
u(:, n_Y, 🙂 = u(:, n_Y-1, :); % Right side wall
v(:, 1, 🙂 = v(:, 2, :); % Left side wall
v(:, n_Y, 🙂 = v(:, n_Y-1, :); % Right side wall
w(:, 1, 🙂 = w(:, 2, :); % Left side wall
w(:, n_Y, 🙂 = w(:, n_Y-1, :); % Right side wall
% Convergence check
max_diff_u = max(max(max(abs(u – u_old))));
max_diff_v = max(max(max(abs(v – v_old))));
max_diff_w = max(max(max(abs(w – w_old))));
max_diff_p = max(max(max(abs(p – p_old))));
disp([‘Max difference in u: ‘, num2str(max_diff_u)]);
disp([‘Max difference in v: ‘, num2str(max_diff_v)]);
disp([‘Max difference in w: ‘, num2str(max_diff_w)]);
disp([‘Max difference in p: ‘, num2str(max_diff_p)]);
if max_diff_u < tolerance && max_diff_v < tolerance && max_diff_w < tolerance && max_diff_p < tolerance
disp(‘Converged’);
break; % Exit the loop if converged
end
% Check for NaN or Inf values
if any(isnan(u(:))) || any(isinf(u(:))) || any(isnan(v(:))) || any(isinf(v(:))) || any(isnan(w(:))) || any(isinf(w(:))) || any(isnan(p(:))) || any(isinf(p(:)))
disp(‘Error: NaN or Inf detected in velocity or pressure matrix’);
break;
end
end clc; % Clear the command window
clear; % Clear all variables
% Input parameters
rho_fluid = 1220;
rho_copper = 8960; % Density of copper in kg/m^3
L_X = 0.0043;
L_Y = 0.0001;
L_Z = 0.0002;
n_X = 300;
n_Y = 50;
n_Z = 50;
u_inlet = 0.05; % Reduced inlet velocity in m/s
nu = 1e-6; % Kinematic viscosity of the fluid (m^2/s)
tolerance = 1e-6; % Convergence tolerance
max_iter = 10000; % Maximum number of iterations
dt = 1e-10; % Further reduced time step for better numerical stability
% Calculate delta
delta_x = L_X / (n_X – 1); % Grid spacing in X direction
delta_y = L_Y / (n_Y – 1); % Grid spacing in Y direction
delta_z = L_Z / (n_Z – 1); % Grid spacing in Z direction
% Define pin positions and dimensions
pin_radius = 0.0001; % Radius of the pins
pin_height = L_Z; % Height of the pins (same as channel height)
pin_positions = [0.001 0.00005; 0.002 0.00005; 0.003 0.00005; 0.0015 0.00005; 0.0025 0.00005]; % X and Y coordinates of pin centers
% Identify grid points inside and on the surface of pins
is_pin = false(n_X, n_Y, n_Z);
is_surface_pin = false(n_X, n_Y, n_Z);
for p = 1:size(pin_positions, 1)
for i = 1:n_X
for j = 1:n_Y
for k = 1:n_Z
x = (i-1) * delta_x;
y = (j-1) * delta_y;
distance = sqrt((x – pin_positions(p, 1))^2 + (y – pin_positions(p, 2))^2);
if distance <= pin_radius
is_pin(i, j, k) = true;
end
if abs(distance – pin_radius) < (delta_x / 2) % Near the surface
is_surface_pin(i, j, k) = true;
end
end
end
end
end
% Initialize velocity and pressure fields
u = zeros(n_X, n_Y, n_Z); % Initialize with zeros to avoid initial instability
v = zeros(n_X, n_Y, n_Z);
w = zeros(n_X, n_Y, n_Z);
p = zeros(n_X, n_Y, n_Z);
% Time-stepping method for solving Navier-Stokes equations using ADI method
for iter = 1:max_iter
u_old = u;
v_old = v;
w_old = w;
p_old = p;
% Solve for velocity fields (x-direction)
for j = 2:n_Y-1
for k = 2:n_Z-1
for i = 2:n_X-1
if ~is_pin(i, j, k)
% x-momentum equation (ADI method)
u(i,j,k) = u_old(i,j,k) + dt/2 * ( …
– u_old(i,j,k) * (u_old(i+1,j,k) – u_old(i-1,j,k)) / (2 * delta_x) …
– v_old(i,j,k) * (u_old(i,j+1,k) – u_old(i,j-1,k)) / (2 * delta_y) …
– w_old(i,j,k) * (u_old(i,j,k+1) – u_old(i,j,k-1)) / (2 * delta_z) …
+ (p_old(i+1,j,k) – p_old(i-1,j,k)) / (2 * delta_x * rho_fluid) …
+ nu * ((u_old(i+1,j,k) – 2*u_old(i,j,k) + u_old(i-1,j,k)) / delta_x^2 …
+ (u_old(i,j+1,k) – 2*u_old(i,j,k) + u_old(i,j-1,k)) / delta_y^2 …
+ (u_old(i,j,k+1) – 2*u_old(i,j,k) + u_old(i,j,k-1)) / delta_z^2) …
);
end
end
end
end
% Solve for velocity fields (y-direction)
for i = 2:n_X-1
for k = 2:n_Z-1
for j = 2:n_Y-1
if ~is_pin(i, j, k)
% y-momentum equation (ADI method)
v(i,j,k) = v_old(i,j,k) + dt/2 * ( …
– u_old(i,j,k) * (v_old(i+1,j,k) – v_old(i-1,j,k)) / (2 * delta_x) …
– v_old(i,j,k) * (v_old(i,j+1,k) – v_old(i,j-1,k)) / (2 * delta_y) …
– w_old(i,j,k) * (v_old(i,j,k+1) – v_old(i,j,k-1)) / (2 * delta_z) …
+ (p_old(i,j+1,k) – p_old(i,j-1,k)) / (2 * delta_y * rho_fluid) …
+ nu * ((v_old(i+1,j,k) – 2*v_old(i,j,k) + v_old(i-1,j,k)) / delta_x^2 …
+ (v_old(i,j+1,k) – 2*v_old(i,j,k) + v_old(i,j-1,k)) / delta_y^2 …
+ (v_old(i,j,k+1) – 2*v_old(i,j,k) + v_old(i,j,k-1)) / delta_z^2) …
);
end
end
end
end
% Solve for velocity fields (z-direction)
for i = 2:n_X-1
for j = 2:n_Y-1
for k = 2:n_Z-1
if ~is_pin(i, j, k)
% z-momentum equation (ADI method)
w(i,j,k) = w_old(i,j,k) + dt/2 * ( …
– u_old(i,j,k) * (w_old(i+1,j,k) – w_old(i-1,j,k)) / (2 * delta_x) …
– v_old(i,j,k) * (w_old(i,j+1,k) – w_old(i,j-1,k)) / (2 * delta_y) …
– w_old(i,j,k) * (w_old(i,j,k+1) – w_old(i,j,k-1)) / (2 * delta_z) …
+ (p_old(i,j,k+1) – p_old(i,j,k-1)) / (2 * delta_z * rho_fluid) …
+ nu * ((w_old(i+1,j,k) – 2*w_old(i,j,k) + w_old(i-1,j,k)) / delta_x^2 …
+ (w_old(i,j+1,k) – 2*w_old(i,j,k) + w_old(i,j-1,k)) / delta_y^2 …
+ (w_old(i,j,k+1) – 2*w_old(i,j,k) + w_old(i,j,k-1)) / delta_z^2) …
);
end
end
end
end
% Solve for pressure field using the pressure Poisson equation
for i = 2:n_X-1
for j = 2:n_Y-1
for k = 2:n_Z-1
if ~is_pin(i, j, k)
p(i,j,k) = (p_old(i+1,j,k) + p_old(i-1,j,k) + p_old(i,j+1,k) + p_old(i,j-1,k) + p_old(i,j,k+1) + p_old(i,j,k-1)) / 6 …
– (rho_fluid / 6) * ((u(i+1,j,k) – u(i-1,j,k)) / (2 * delta_x) …
+ (v(i,j+1,k) – v(i,j-1,k)) / (2 * delta_y) …
+ (w(i,j,k+1) – w(i,j,k-1)) / (2 * delta_z));
end
end
end
end
% Inlet boundary condition for velocity
u(1, :, 🙂 = u_inlet;
% Outlet boundary condition for pressure
p(n_X, :, 🙂 = 0; % Assume atmospheric pressure at the outlet
% No-slip boundary conditions for velocity at the walls and pins
u(:, :, 1) = 0; % Bottom wall
u(:, :, n_Z) = 0; % Top wall
u(is_pin) = 0; % Surface of pins
v(:, :, 1) = 0; % Bottom wall
v(:, :, n_Z) = 0; % Top wall
v(is_pin) = 0; % Surface of pins
w(:, :, 1) = 0; % Bottom wall
w(:, :, n_Z) = 0; % Top wall
w(is_pin) = 0; % Surface of pins
% Symmetry boundary conditions for velocity at the side walls
u(:, 1, 🙂 = u(:, 2, :); % Left side wall
u(:, n_Y, 🙂 = u(:, n_Y-1, :); % Right side wall
v(:, 1, 🙂 = v(:, 2, :); % Left side wall
v(:, n_Y, 🙂 = v(:, n_Y-1, :); % Right side wall
w(:, 1, 🙂 = w(:, 2, :); % Left side wall
w(:, n_Y, 🙂 = w(:, n_Y-1, :); % Right side wall
% Convergence check
max_diff_u = max(max(max(abs(u – u_old))));
max_diff_v = max(max(max(abs(v – v_old))));
max_diff_w = max(max(max(abs(w – w_old))));
max_diff_p = max(max(max(abs(p – p_old))));
disp([‘Max difference in u: ‘, num2str(max_diff_u)]);
disp([‘Max difference in v: ‘, num2str(max_diff_v)]);
disp([‘Max difference in w: ‘, num2str(max_diff_w)]);
disp([‘Max difference in p: ‘, num2str(max_diff_p)]);
if max_diff_u < tolerance && max_diff_v < tolerance && max_diff_w < tolerance && max_diff_p < tolerance
disp(‘Converged’);
break; % Exit the loop if converged
end
% Check for NaN or Inf values
if any(isnan(u(:))) || any(isinf(u(:))) || any(isnan(v(:))) || any(isinf(v(:))) || any(isnan(w(:))) || any(isinf(w(:))) || any(isnan(p(:))) || any(isinf(p(:)))
disp(‘Error: NaN or Inf detected in velocity or pressure matrix’);
break;
end
end navier-stocks divergence MATLAB Answers — New Questions