Author: PuTI
Parallel processing is not able to use all my cores
I have the same problem.
The SuperMicro MBD-H12DSI-N6-B motherboard has 2 x 48-core AMD EPYC 7K62 processors.
But MATLAB (R2024a) sees only one of them and opens a pool with 48 workers.
When multiplying and inverting matrices, the dual-processor system load is 50…65%.
The operating system is Microsoft Windows 10 Pro for Workstations 22H2.
The maxNumCompThreads command produces the following result:
>> N = maxNumCompThreads
N =
48
An attempt to set the maximum number of workers to 96 succeeds:
>> LASTN = maxNumCompThreads(96)
LASTN =
48
>> N = maxNumCompThreads
N =
96
But after that, a pool is opened with 48 workers as well:
>> parpool
Starting parallel pool (parpool) using the ‘Processes’ profile …
Connected to parallel pool with 48 workers.
ans =
ProcessPool with properties:
Connected: true
NumWorkers: 48
However, I did not find in the settings where I can set the maximum number of workers.
The feature(‘numcores’) command produces the following result:
>> feature(‘numcores’)
MATLAB detected: 96 physical cores.
MATLAB detected: 96 logical cores.
MATLAB was assigned: 48 logical cores by the OS.
MATLAB is using: 48 logical cores.
MATLAB is not using all logical cores because Operating System restricted the number of cores to: 48.
ans =
48
That is, MATLAB complains about the Windows operating system
What to do?
Is it possible to run all 96 cores?I have the same problem.
The SuperMicro MBD-H12DSI-N6-B motherboard has 2 x 48-core AMD EPYC 7K62 processors.
But MATLAB (R2024a) sees only one of them and opens a pool with 48 workers.
When multiplying and inverting matrices, the dual-processor system load is 50…65%.
The operating system is Microsoft Windows 10 Pro for Workstations 22H2.
The maxNumCompThreads command produces the following result:
>> N = maxNumCompThreads
N =
48
An attempt to set the maximum number of workers to 96 succeeds:
>> LASTN = maxNumCompThreads(96)
LASTN =
48
>> N = maxNumCompThreads
N =
96
But after that, a pool is opened with 48 workers as well:
>> parpool
Starting parallel pool (parpool) using the ‘Processes’ profile …
Connected to parallel pool with 48 workers.
ans =
ProcessPool with properties:
Connected: true
NumWorkers: 48
However, I did not find in the settings where I can set the maximum number of workers.
The feature(‘numcores’) command produces the following result:
>> feature(‘numcores’)
MATLAB detected: 96 physical cores.
MATLAB detected: 96 logical cores.
MATLAB was assigned: 48 logical cores by the OS.
MATLAB is using: 48 logical cores.
MATLAB is not using all logical cores because Operating System restricted the number of cores to: 48.
ans =
48
That is, MATLAB complains about the Windows operating system
What to do?
Is it possible to run all 96 cores? I have the same problem.
The SuperMicro MBD-H12DSI-N6-B motherboard has 2 x 48-core AMD EPYC 7K62 processors.
But MATLAB (R2024a) sees only one of them and opens a pool with 48 workers.
When multiplying and inverting matrices, the dual-processor system load is 50…65%.
The operating system is Microsoft Windows 10 Pro for Workstations 22H2.
The maxNumCompThreads command produces the following result:
>> N = maxNumCompThreads
N =
48
An attempt to set the maximum number of workers to 96 succeeds:
>> LASTN = maxNumCompThreads(96)
LASTN =
48
>> N = maxNumCompThreads
N =
96
But after that, a pool is opened with 48 workers as well:
>> parpool
Starting parallel pool (parpool) using the ‘Processes’ profile …
Connected to parallel pool with 48 workers.
ans =
ProcessPool with properties:
Connected: true
NumWorkers: 48
However, I did not find in the settings where I can set the maximum number of workers.
The feature(‘numcores’) command produces the following result:
>> feature(‘numcores’)
MATLAB detected: 96 physical cores.
MATLAB detected: 96 logical cores.
MATLAB was assigned: 48 logical cores by the OS.
MATLAB is using: 48 logical cores.
MATLAB is not using all logical cores because Operating System restricted the number of cores to: 48.
ans =
48
That is, MATLAB complains about the Windows operating system
What to do?
Is it possible to run all 96 cores? parallel processing MATLAB Answers — New Questions
Analytic solution of quatric polynomial does not add up
Dear friends,
I currently ran into a math-issue when trying to get the analytical roots of a polynomial of order 4.
What I want to solve is:
The solution shall run on a microcontroller with dynamically changing parameters [a,d,e]. All parameters are real. I am searching for the real results, imaginary solutions are to be prevented. When applying Matlab symbolic, The parameters [a,d,e] are simplified and represent longer sub-terms. In accordance to the article Wiki: quartic function, I will receive quite a long solution, that is futile to reproduce here. I used the following short code to generate it:
syms x a d e
y= a*x^4+d*x+e
sol=solve(y==0,x,’MaxDegree’,4,’ReturnConditions’,true)
To check the solution, I tested it on an easier sub-problem: When d=0 is chosen follows:
When chosing a>0, e<0 this clearly yields some real results, besides the imaginary ones. Now the problem: the above given long solution cannot reproduce this result. Even if I force assumptions that should solve it, follows something that does not look equal:
syms x a d e
assume(a>=0)
assume(d>=0)
assume(e<=0)
y= a*x^4+d*x+e
sol=solve(y==0,x,’MaxDegree’,4,’ReturnConditions’,true)
testresult=simplify(subs(sol.x, d,0))
latex(testresult)
However, if I change the equation before solving the quartic function, the solution of it looks as on paper:
y= a*x^4+e
assume(a>=0)
assume(d>=0)
assume(e<=0)
sol=solve(y==0,x,’MaxDegree’,4,’ReturnConditions’,true)
testresult2=sol.x
latex(testresult2)
Numerical testing via inserting numbers in the two solutions according to the assumptions a>0, e<0 confirms the difference of the results. Chosing a=1 and e=-2 yields:
1) the general solution of the quartic polynomial (inserting d=0 after solving the quartic polynomial):
vpares1=vpa(subs(testresult,{a,e},{1,-2}))
vpares1 =
0
0
0
0
2) the solution of the simplified quartic polynomial (inserting d=0 before solving):
vpares2=vpa(subs(testresult2,{a,e},{1,-2}))
vpares2 =
1.1892071150027210667174999705605
-1.1892071150027210667174999705605
-1.1892071150027210667174999705605i
1.1892071150027210667174999705605i
Visibly, the trivial solution is not permissible given the solution of case 2). Interestingly, if the requirement is switched from {a>0,e<0} to {a<0, e>0} the solutions match again.
Similar difficulties have shown, when I hand-coded the general solution from the mentioned Wikipedia article. As I need the solution for , I now have trust-issues with the long solution. Therefore, I ask for your help or comment, why the "general solution" does not end in the same result as the simplified problem.
Thank you in advance for your help!Dear friends,
I currently ran into a math-issue when trying to get the analytical roots of a polynomial of order 4.
What I want to solve is:
The solution shall run on a microcontroller with dynamically changing parameters [a,d,e]. All parameters are real. I am searching for the real results, imaginary solutions are to be prevented. When applying Matlab symbolic, The parameters [a,d,e] are simplified and represent longer sub-terms. In accordance to the article Wiki: quartic function, I will receive quite a long solution, that is futile to reproduce here. I used the following short code to generate it:
syms x a d e
y= a*x^4+d*x+e
sol=solve(y==0,x,’MaxDegree’,4,’ReturnConditions’,true)
To check the solution, I tested it on an easier sub-problem: When d=0 is chosen follows:
When chosing a>0, e<0 this clearly yields some real results, besides the imaginary ones. Now the problem: the above given long solution cannot reproduce this result. Even if I force assumptions that should solve it, follows something that does not look equal:
syms x a d e
assume(a>=0)
assume(d>=0)
assume(e<=0)
y= a*x^4+d*x+e
sol=solve(y==0,x,’MaxDegree’,4,’ReturnConditions’,true)
testresult=simplify(subs(sol.x, d,0))
latex(testresult)
However, if I change the equation before solving the quartic function, the solution of it looks as on paper:
y= a*x^4+e
assume(a>=0)
assume(d>=0)
assume(e<=0)
sol=solve(y==0,x,’MaxDegree’,4,’ReturnConditions’,true)
testresult2=sol.x
latex(testresult2)
Numerical testing via inserting numbers in the two solutions according to the assumptions a>0, e<0 confirms the difference of the results. Chosing a=1 and e=-2 yields:
1) the general solution of the quartic polynomial (inserting d=0 after solving the quartic polynomial):
vpares1=vpa(subs(testresult,{a,e},{1,-2}))
vpares1 =
0
0
0
0
2) the solution of the simplified quartic polynomial (inserting d=0 before solving):
vpares2=vpa(subs(testresult2,{a,e},{1,-2}))
vpares2 =
1.1892071150027210667174999705605
-1.1892071150027210667174999705605
-1.1892071150027210667174999705605i
1.1892071150027210667174999705605i
Visibly, the trivial solution is not permissible given the solution of case 2). Interestingly, if the requirement is switched from {a>0,e<0} to {a<0, e>0} the solutions match again.
Similar difficulties have shown, when I hand-coded the general solution from the mentioned Wikipedia article. As I need the solution for , I now have trust-issues with the long solution. Therefore, I ask for your help or comment, why the "general solution" does not end in the same result as the simplified problem.
Thank you in advance for your help! Dear friends,
I currently ran into a math-issue when trying to get the analytical roots of a polynomial of order 4.
What I want to solve is:
The solution shall run on a microcontroller with dynamically changing parameters [a,d,e]. All parameters are real. I am searching for the real results, imaginary solutions are to be prevented. When applying Matlab symbolic, The parameters [a,d,e] are simplified and represent longer sub-terms. In accordance to the article Wiki: quartic function, I will receive quite a long solution, that is futile to reproduce here. I used the following short code to generate it:
syms x a d e
y= a*x^4+d*x+e
sol=solve(y==0,x,’MaxDegree’,4,’ReturnConditions’,true)
To check the solution, I tested it on an easier sub-problem: When d=0 is chosen follows:
When chosing a>0, e<0 this clearly yields some real results, besides the imaginary ones. Now the problem: the above given long solution cannot reproduce this result. Even if I force assumptions that should solve it, follows something that does not look equal:
syms x a d e
assume(a>=0)
assume(d>=0)
assume(e<=0)
y= a*x^4+d*x+e
sol=solve(y==0,x,’MaxDegree’,4,’ReturnConditions’,true)
testresult=simplify(subs(sol.x, d,0))
latex(testresult)
However, if I change the equation before solving the quartic function, the solution of it looks as on paper:
y= a*x^4+e
assume(a>=0)
assume(d>=0)
assume(e<=0)
sol=solve(y==0,x,’MaxDegree’,4,’ReturnConditions’,true)
testresult2=sol.x
latex(testresult2)
Numerical testing via inserting numbers in the two solutions according to the assumptions a>0, e<0 confirms the difference of the results. Chosing a=1 and e=-2 yields:
1) the general solution of the quartic polynomial (inserting d=0 after solving the quartic polynomial):
vpares1=vpa(subs(testresult,{a,e},{1,-2}))
vpares1 =
0
0
0
0
2) the solution of the simplified quartic polynomial (inserting d=0 before solving):
vpares2=vpa(subs(testresult2,{a,e},{1,-2}))
vpares2 =
1.1892071150027210667174999705605
-1.1892071150027210667174999705605
-1.1892071150027210667174999705605i
1.1892071150027210667174999705605i
Visibly, the trivial solution is not permissible given the solution of case 2). Interestingly, if the requirement is switched from {a>0,e<0} to {a<0, e>0} the solutions match again.
Similar difficulties have shown, when I hand-coded the general solution from the mentioned Wikipedia article. As I need the solution for , I now have trust-issues with the long solution. Therefore, I ask for your help or comment, why the "general solution" does not end in the same result as the simplified problem.
Thank you in advance for your help! mathematics, symbolic, 4th order polynomial, polynomial MATLAB Answers — New Questions
Fatal error starting Matlab 1. time in Ubuntu 25.04
Starting Matlab in CLI on an Ubuntu 25.04 with 16 Gb of RAM I get this:
MATLAB is selecting SOFTWARE OPENGL rendering.
Fontconfig warning: "/usr/share/fontconfig/conf.avail/05-reset-dirs-sample.conf", line 6: unknown element "reset-dirs"
library initialization failed – unable to allocate file descriptor table – out of memory
MATLAB is exiting because of fatal error.
I have installed to /home/pgl/matlab as a user (not su).
What is the issue?
Best
PålStarting Matlab in CLI on an Ubuntu 25.04 with 16 Gb of RAM I get this:
MATLAB is selecting SOFTWARE OPENGL rendering.
Fontconfig warning: "/usr/share/fontconfig/conf.avail/05-reset-dirs-sample.conf", line 6: unknown element "reset-dirs"
library initialization failed – unable to allocate file descriptor table – out of memory
MATLAB is exiting because of fatal error.
I have installed to /home/pgl/matlab as a user (not su).
What is the issue?
Best
Pål Starting Matlab in CLI on an Ubuntu 25.04 with 16 Gb of RAM I get this:
MATLAB is selecting SOFTWARE OPENGL rendering.
Fontconfig warning: "/usr/share/fontconfig/conf.avail/05-reset-dirs-sample.conf", line 6: unknown element "reset-dirs"
library initialization failed – unable to allocate file descriptor table – out of memory
MATLAB is exiting because of fatal error.
I have installed to /home/pgl/matlab as a user (not su).
What is the issue?
Best
Pål ubuntu 25.04, font rendering, opengl MATLAB Answers — New Questions
Errors in listener callbacks
I have an app built in MATLAB App Designer. the underlying code utlizes events and listeners. my problem is this: Whenever an error occurs in the code, the app needs to know about this. when the error occurs in the code itself, there are built in "catch" commands that notify the GUI.
However, when an error occurs in one of the listener callbacks, there is some built in mechanism that replaces the error with a warning. Instead of getting an error message we get a warning: "error occurred during execution of listener callback" and a description of the error message.
Is there a way to cancel this mechanism? to let the errors in listener callbacks become actual error messages? or maybe a way to notify the app in case of a warning? something like try catch that includes warnings?
many thanks
NathanI have an app built in MATLAB App Designer. the underlying code utlizes events and listeners. my problem is this: Whenever an error occurs in the code, the app needs to know about this. when the error occurs in the code itself, there are built in "catch" commands that notify the GUI.
However, when an error occurs in one of the listener callbacks, there is some built in mechanism that replaces the error with a warning. Instead of getting an error message we get a warning: "error occurred during execution of listener callback" and a description of the error message.
Is there a way to cancel this mechanism? to let the errors in listener callbacks become actual error messages? or maybe a way to notify the app in case of a warning? something like try catch that includes warnings?
many thanks
Nathan I have an app built in MATLAB App Designer. the underlying code utlizes events and listeners. my problem is this: Whenever an error occurs in the code, the app needs to know about this. when the error occurs in the code itself, there are built in "catch" commands that notify the GUI.
However, when an error occurs in one of the listener callbacks, there is some built in mechanism that replaces the error with a warning. Instead of getting an error message we get a warning: "error occurred during execution of listener callback" and a description of the error message.
Is there a way to cancel this mechanism? to let the errors in listener callbacks become actual error messages? or maybe a way to notify the app in case of a warning? something like try catch that includes warnings?
many thanks
Nathan app designer, listener, event, callback, error MATLAB Answers — New Questions
DDPG Agent for Battery Control: Scalar action vs Full trajectory?
I’m implementing a Reinforcement Learning solution to control a home battery, similar to a Model Predictive Control (MPC) approach. The observation includes the current state of charge (SoC) and N-step forecasts for PV generation, electrical demand, import price, and export price.
In MPC, I calculate an optimal charge/discharge trajectory over the prediction horizon and output the entire plan. Now, I’m trying to implement the same using a DDPG agent in MATLAB.
My questions:
Should the DDPG agent output a scalar action (charging/discharging power) for each timestep, which is then used to update the SoC based on the sampling time,
or should the agent output a full trajectory, where I execute only the first action but discard the remaining ones, while still using the full trajectory for the reward calculation?
My thoughts:
In MPC, I get the entire optimal trajectory for charging and discharging over the horizon. Initially, I considered using the same approach with the DDPG agent. However, I’m wondering if this is necessary because the value function already accounts for downstream benefits (future prices/loads) since they are included in the state, right?
But if the agent returns just one action for the next state, it seems like this would lead to a result similar to what I would get if I had no prediction horizon at all.
Thanks in advance for any suggestions.I’m implementing a Reinforcement Learning solution to control a home battery, similar to a Model Predictive Control (MPC) approach. The observation includes the current state of charge (SoC) and N-step forecasts for PV generation, electrical demand, import price, and export price.
In MPC, I calculate an optimal charge/discharge trajectory over the prediction horizon and output the entire plan. Now, I’m trying to implement the same using a DDPG agent in MATLAB.
My questions:
Should the DDPG agent output a scalar action (charging/discharging power) for each timestep, which is then used to update the SoC based on the sampling time,
or should the agent output a full trajectory, where I execute only the first action but discard the remaining ones, while still using the full trajectory for the reward calculation?
My thoughts:
In MPC, I get the entire optimal trajectory for charging and discharging over the horizon. Initially, I considered using the same approach with the DDPG agent. However, I’m wondering if this is necessary because the value function already accounts for downstream benefits (future prices/loads) since they are included in the state, right?
But if the agent returns just one action for the next state, it seems like this would lead to a result similar to what I would get if I had no prediction horizon at all.
Thanks in advance for any suggestions. I’m implementing a Reinforcement Learning solution to control a home battery, similar to a Model Predictive Control (MPC) approach. The observation includes the current state of charge (SoC) and N-step forecasts for PV generation, electrical demand, import price, and export price.
In MPC, I calculate an optimal charge/discharge trajectory over the prediction horizon and output the entire plan. Now, I’m trying to implement the same using a DDPG agent in MATLAB.
My questions:
Should the DDPG agent output a scalar action (charging/discharging power) for each timestep, which is then used to update the SoC based on the sampling time,
or should the agent output a full trajectory, where I execute only the first action but discard the remaining ones, while still using the full trajectory for the reward calculation?
My thoughts:
In MPC, I get the entire optimal trajectory for charging and discharging over the horizon. Initially, I considered using the same approach with the DDPG agent. However, I’m wondering if this is necessary because the value function already accounts for downstream benefits (future prices/loads) since they are included in the state, right?
But if the agent returns just one action for the next state, it seems like this would lead to a result similar to what I would get if I had no prediction horizon at all.
Thanks in advance for any suggestions. reinforcement-learning, ddpg, simulink, mpc, matlab MATLAB Answers — New Questions
TreeTable in Matlab 2025a
Since javacomponents are deprecated as of MATLAB 2025a, has anyone found a way to generate treetables similar to what was possible with jide ?
We have been relying on those for a lot of GUI and see nothing in UITABLE/UITREE that would be similar. Necessary features are
tree opening
resizable columns
cell renderer allowing push buttons and pull down menus
column sorting is a bonusSince javacomponents are deprecated as of MATLAB 2025a, has anyone found a way to generate treetables similar to what was possible with jide ?
We have been relying on those for a lot of GUI and see nothing in UITABLE/UITREE that would be similar. Necessary features are
tree opening
resizable columns
cell renderer allowing push buttons and pull down menus
column sorting is a bonus Since javacomponents are deprecated as of MATLAB 2025a, has anyone found a way to generate treetables similar to what was possible with jide ?
We have been relying on those for a lot of GUI and see nothing in UITABLE/UITREE that would be similar. Necessary features are
tree opening
resizable columns
cell renderer allowing push buttons and pull down menus
column sorting is a bonus uitable, uitree, treetable MATLAB Answers — New Questions
Please help me to run this simple code. I want to check the definition the third oder of ODE is true of false in projfun function.
where c,alfa,mu,beta are constant.
% code
function sol= proj
clc;clf;clear;
myLegend1 = {};myLegend2 = {};
rr = [0.8]
for i =1:numel(rr)
c= rr(i);
alfa=6;
b=6;nu=4;
y0 = [1,1,1];
options =bvpset(‘stats’,’on’,’RelTol’,1e-4);
m = linspace(-3,3);
solinit = bvpinit(m,y0);
sol= bvp4c(@projfun,@projbc,solinit,options);
figure(1)
% plot(sol.x,(sol.y(1,:)))
yExact=nu*(3/b)*(sech((sqrt(nu)*0.5)*sol.x)).^2;
plot(sol.x,(sol.y(1,:)),’r’,sol.x,yExact,’b’)
grid on,hold on
myLegend1{i}=[‘b1= ‘,num2str(rr(i))];
% figure(2)
% % plot(sol.x,(sol.y(1,:)))
% grid on,hold on
% myLegend2{i}=[‘b1= ‘,num2str(rr(i))];
i=i+1;
end
figure(1)
legend(myLegend1)
hold on
figure(2)
legend(myLegend2)
function dy= projfun(~,y)
dy= zeros(3,1);
E = y(1);
dE = y(2);
ddE=y(3);
dy(1) = dE;
dy(2) =ddE;
dy(3)=(1/b)*(nu*ddE+dE*(c-alfa*E));
end
end
function res= projbc(ya,yb)
res= [ya(1);
ya(2);
yb(1);
];
endwhere c,alfa,mu,beta are constant.
% code
function sol= proj
clc;clf;clear;
myLegend1 = {};myLegend2 = {};
rr = [0.8]
for i =1:numel(rr)
c= rr(i);
alfa=6;
b=6;nu=4;
y0 = [1,1,1];
options =bvpset(‘stats’,’on’,’RelTol’,1e-4);
m = linspace(-3,3);
solinit = bvpinit(m,y0);
sol= bvp4c(@projfun,@projbc,solinit,options);
figure(1)
% plot(sol.x,(sol.y(1,:)))
yExact=nu*(3/b)*(sech((sqrt(nu)*0.5)*sol.x)).^2;
plot(sol.x,(sol.y(1,:)),’r’,sol.x,yExact,’b’)
grid on,hold on
myLegend1{i}=[‘b1= ‘,num2str(rr(i))];
% figure(2)
% % plot(sol.x,(sol.y(1,:)))
% grid on,hold on
% myLegend2{i}=[‘b1= ‘,num2str(rr(i))];
i=i+1;
end
figure(1)
legend(myLegend1)
hold on
figure(2)
legend(myLegend2)
function dy= projfun(~,y)
dy= zeros(3,1);
E = y(1);
dE = y(2);
ddE=y(3);
dy(1) = dE;
dy(2) =ddE;
dy(3)=(1/b)*(nu*ddE+dE*(c-alfa*E));
end
end
function res= projbc(ya,yb)
res= [ya(1);
ya(2);
yb(1);
];
end where c,alfa,mu,beta are constant.
% code
function sol= proj
clc;clf;clear;
myLegend1 = {};myLegend2 = {};
rr = [0.8]
for i =1:numel(rr)
c= rr(i);
alfa=6;
b=6;nu=4;
y0 = [1,1,1];
options =bvpset(‘stats’,’on’,’RelTol’,1e-4);
m = linspace(-3,3);
solinit = bvpinit(m,y0);
sol= bvp4c(@projfun,@projbc,solinit,options);
figure(1)
% plot(sol.x,(sol.y(1,:)))
yExact=nu*(3/b)*(sech((sqrt(nu)*0.5)*sol.x)).^2;
plot(sol.x,(sol.y(1,:)),’r’,sol.x,yExact,’b’)
grid on,hold on
myLegend1{i}=[‘b1= ‘,num2str(rr(i))];
% figure(2)
% % plot(sol.x,(sol.y(1,:)))
% grid on,hold on
% myLegend2{i}=[‘b1= ‘,num2str(rr(i))];
i=i+1;
end
figure(1)
legend(myLegend1)
hold on
figure(2)
legend(myLegend2)
function dy= projfun(~,y)
dy= zeros(3,1);
E = y(1);
dE = y(2);
ddE=y(3);
dy(1) = dE;
dy(2) =ddE;
dy(3)=(1/b)*(nu*ddE+dE*(c-alfa*E));
end
end
function res= projbc(ya,yb)
res= [ya(1);
ya(2);
yb(1);
];
end bvp4c, ode MATLAB Answers — New Questions
How can I add a backup an option, addSaveCallback, to save a timestamped version of my file, to the MATLAB editor?
% I’d like to add the option to save backup files – earlier versions every time I save a file in the Matlab editor
editorObj = matlab.desktop.editor.getActive;
editorObj.addSaveCallback(@mySaveCallback);
function mySaveCallback(~, ~)
disp(‘File has been saved!’);
% Add your custom code here
saveBackup(originalFilePath);
end
function saveBackup(originalFilePath)
% Check if the file exists
if ~isfile(originalFilePath)
error(‘The specified file does not exist.’);
end
% Extract file parts
[filePath, fileName, fileExt] = fileparts(originalFilePath);
% Create a timestamp
timestamp = datestr(now, ‘yyyymmdd_HHMMSS’);
% Define the backup file name
backupFileName = sprintf(‘%s_backup_%s%s’, fileName, timestamp, fileExt);
backupFilePath = fullfile(filePath, backupFileName);
% Copy the file to create a backup
copyfile(originalFilePath, backupFilePath);
fprintf(‘Backup saved as: %sn’, backupFilePath);
end% I’d like to add the option to save backup files – earlier versions every time I save a file in the Matlab editor
editorObj = matlab.desktop.editor.getActive;
editorObj.addSaveCallback(@mySaveCallback);
function mySaveCallback(~, ~)
disp(‘File has been saved!’);
% Add your custom code here
saveBackup(originalFilePath);
end
function saveBackup(originalFilePath)
% Check if the file exists
if ~isfile(originalFilePath)
error(‘The specified file does not exist.’);
end
% Extract file parts
[filePath, fileName, fileExt] = fileparts(originalFilePath);
% Create a timestamp
timestamp = datestr(now, ‘yyyymmdd_HHMMSS’);
% Define the backup file name
backupFileName = sprintf(‘%s_backup_%s%s’, fileName, timestamp, fileExt);
backupFilePath = fullfile(filePath, backupFileName);
% Copy the file to create a backup
copyfile(originalFilePath, backupFilePath);
fprintf(‘Backup saved as: %sn’, backupFilePath);
end % I’d like to add the option to save backup files – earlier versions every time I save a file in the Matlab editor
editorObj = matlab.desktop.editor.getActive;
editorObj.addSaveCallback(@mySaveCallback);
function mySaveCallback(~, ~)
disp(‘File has been saved!’);
% Add your custom code here
saveBackup(originalFilePath);
end
function saveBackup(originalFilePath)
% Check if the file exists
if ~isfile(originalFilePath)
error(‘The specified file does not exist.’);
end
% Extract file parts
[filePath, fileName, fileExt] = fileparts(originalFilePath);
% Create a timestamp
timestamp = datestr(now, ‘yyyymmdd_HHMMSS’);
% Define the backup file name
backupFileName = sprintf(‘%s_backup_%s%s’, fileName, timestamp, fileExt);
backupFilePath = fullfile(filePath, backupFileName);
% Copy the file to create a backup
copyfile(originalFilePath, backupFilePath);
fprintf(‘Backup saved as: %sn’, backupFilePath);
end matlab, editor, backup MATLAB Answers — New Questions
I need to remove tool boxes that were chosen when matlab was configured. How do I do that
Previously Matlab was mistakenly installed with all toolboxes selected for many installations. Now we are running into problems with licensing. I need to go in to these instances and undo those toolbox selections. Not sure the best way to do that.Previously Matlab was mistakenly installed with all toolboxes selected for many installations. Now we are running into problems with licensing. I need to go in to these instances and undo those toolbox selections. Not sure the best way to do that. Previously Matlab was mistakenly installed with all toolboxes selected for many installations. Now we are running into problems with licensing. I need to go in to these instances and undo those toolbox selections. Not sure the best way to do that. uninstall tool boxes MATLAB Answers — New Questions
How can I write a MATLAB script to plot 3D and 2D knee joint data from a CSV file with customized axes and medial–lateral connections?
The CSV file contains the following data:
Sensor names: sensorNames = data.Sensor(1:6,1)
Sensor coordinates: sensorCoordinates = data{1:6, 2:4}
Source number: (:,5)
Source coordinates: sourceCoordinates = data{:, 6:end}
I want to create a 3D plot in MATLAB that includes the following:
Plot the sensor names and their coordinates.
Plot the source coordinates. The source coordinates are categorized into two groups:
Medial: sourceCoordinates = data{7:end, 6:end}
Lateral: sourceCoordinates = data{1:6, 6:end}
3. Set the axis directions depending on the knee side (see figure. 1 below), using S2 as the reference sensor (0,0,0):
Figure.1
Right knee: X-axis positive leftward, Y-axis positive downward, Z-axis positive perpendicular to the depth of the plane.
Left knee: X-axis positive rightward, Y-axis positive downward, Z-axis positive perpendicular to the depth of the plane.
4. Generate three types of plots (similar to the figure.2):
A 3D plot with all axes.
A 2D plot of X vs. Y.
A 2D plot of X vs. Z.
5. Add a line (like the green line in the figure.2 below) that connects the medial and lateral sources. This line should represent the knee joint range in all axis directions.
Figure.2
Knee joint range determination table.
I would like to write a MATLAB script that reads the CSV file, extracts the relevant data, and generates the 3D and 2D plots including the above details.
I wrote the following code:
%% Read and Plot 3D/2D Data from CSV File
% Load the CSV file
filename = ‘3DPlot_KLII_Mori.csv’;
data = readtable(filename);
%% Extract Sensor and Source Data
sensorNames = data.Sensor(1:6, 1); % Sensor names
sensorCoordinates = data{1:6, 2:4}; % Sensor coordinates (X, Y, Z)
sourceNumbers = data{:, 5}; % Source numbers
sourceCoordinates = data{:, 6:end}; % All source coordinates
% Categorize source coordinates
lateralSources = data{1:6, 6:end}; % Lateral sources
medialSources = data{7:end, 6:end}; % Medial sources
%% User input for knee side
kneeSide = "Right"; % Change to "Left" if left knee
% Adjust axis directions based on knee side
if strcmpi(kneeSide, "Right")
% Right knee: X positive leftward, Y downward, Z downward
sensorCoordinates(:,1) = -sensorCoordinates(:,1);
lateralSources(:,1) = -lateralSources(:,1);
medialSources(:,1) = -medialSources(:,1);
elseif strcmpi(kneeSide, "Left")
% Left knee: X positive rightward, Y downward, Z downward
% No inversion needed
else
error(‘Knee side must be either "Right" or "Left".’);
end
%% Plotting – 3D Plot
figure;
hold on;
% Plot sensor coordinates
scatter3(sensorCoordinates(:,1), sensorCoordinates(:,2), sensorCoordinates(:,3), …
80, ‘filled’, ‘MarkerFaceColor’, ‘b’);
% Add sensor name labels
for i = 1:length(sensorNames)
text(sensorCoordinates(i,1), sensorCoordinates(i,2), sensorCoordinates(i,3), …
[‘ ‘ char(sensorNames{i})], ‘FontSize’, 10, ‘Color’, ‘b’);
end
% Plot lateral sources
scatter3(lateralSources(:,1), lateralSources(:,2), lateralSources(:,3), …
60, ‘o’, ‘MarkerEdgeColor’, ‘r’, ‘DisplayName’, ‘Lateral Sources’);
% Plot medial sources
scatter3(medialSources(:,1), medialSources(:,2), medialSources(:,3), …
60, ‘s’, ‘MarkerEdgeColor’, ‘g’, ‘DisplayName’, ‘Medial Sources’);
%% Formatting for 3D plot
grid on;
xlabel(‘X-axis’);
ylabel(‘Y-axis’);
zlabel(‘Z-axis’);
title([‘3D Plot of Sensors and Sources (‘ kneeSide ‘ Knee)’]);
legend;
view(3);
hold off;
%% Plotting – 2D Plot (X vs Y)
figure;
hold on;
scatter(sensorCoordinates(:,1), sensorCoordinates(:,2), 80, ‘filled’, ‘b’);
for i = 1:length(sensorNames)
text(sensorCoordinates(i,1), sensorCoordinates(i,2), [‘ ‘ char(sensorNames{i})], ‘FontSize’, 10, ‘Color’, ‘b’);
end
scatter(lateralSources(:,1), lateralSources(:,2), 60, ‘ro’, ‘DisplayName’, ‘Lateral Sources’);
scatter(medialSources(:,1), medialSources(:,2), 60, ‘gs’, ‘DisplayName’, ‘Medial Sources’);
xlabel(‘X-axis’);
ylabel(‘Y-axis’);
title([‘2D Plot (X vs Y) – ‘ kneeSide ‘ Knee’]);
legend;
grid on;
hold off;
%% Plotting – 2D Plot (X vs Z)
figure;
hold on;
scatter(sensorCoordinates(:,1), sensorCoordinates(:,3), 80, ‘filled’, ‘b’);
for i = 1:length(sensorNames)
text(sensorCoordinates(i,1), sensorCoordinates(i,3), [‘ ‘ char(sensorNames{i})], ‘FontSize’, 10, ‘Color’, ‘b’);
end
scatter(lateralSources(:,1), lateralSources(:,3), 60, ‘ro’, ‘DisplayName’, ‘Lateral Sources’);
scatter(medialSources(:,1), medialSources(:,3), 60, ‘gs’, ‘DisplayName’, ‘Medial Sources’);
xlabel(‘X-axis’);
ylabel(‘Z-axis’);
title([‘2D Plot (X vs Z) – ‘ kneeSide ‘ Knee’]);
legend;
grid on;
hold off;The CSV file contains the following data:
Sensor names: sensorNames = data.Sensor(1:6,1)
Sensor coordinates: sensorCoordinates = data{1:6, 2:4}
Source number: (:,5)
Source coordinates: sourceCoordinates = data{:, 6:end}
I want to create a 3D plot in MATLAB that includes the following:
Plot the sensor names and their coordinates.
Plot the source coordinates. The source coordinates are categorized into two groups:
Medial: sourceCoordinates = data{7:end, 6:end}
Lateral: sourceCoordinates = data{1:6, 6:end}
3. Set the axis directions depending on the knee side (see figure. 1 below), using S2 as the reference sensor (0,0,0):
Figure.1
Right knee: X-axis positive leftward, Y-axis positive downward, Z-axis positive perpendicular to the depth of the plane.
Left knee: X-axis positive rightward, Y-axis positive downward, Z-axis positive perpendicular to the depth of the plane.
4. Generate three types of plots (similar to the figure.2):
A 3D plot with all axes.
A 2D plot of X vs. Y.
A 2D plot of X vs. Z.
5. Add a line (like the green line in the figure.2 below) that connects the medial and lateral sources. This line should represent the knee joint range in all axis directions.
Figure.2
Knee joint range determination table.
I would like to write a MATLAB script that reads the CSV file, extracts the relevant data, and generates the 3D and 2D plots including the above details.
I wrote the following code:
%% Read and Plot 3D/2D Data from CSV File
% Load the CSV file
filename = ‘3DPlot_KLII_Mori.csv’;
data = readtable(filename);
%% Extract Sensor and Source Data
sensorNames = data.Sensor(1:6, 1); % Sensor names
sensorCoordinates = data{1:6, 2:4}; % Sensor coordinates (X, Y, Z)
sourceNumbers = data{:, 5}; % Source numbers
sourceCoordinates = data{:, 6:end}; % All source coordinates
% Categorize source coordinates
lateralSources = data{1:6, 6:end}; % Lateral sources
medialSources = data{7:end, 6:end}; % Medial sources
%% User input for knee side
kneeSide = "Right"; % Change to "Left" if left knee
% Adjust axis directions based on knee side
if strcmpi(kneeSide, "Right")
% Right knee: X positive leftward, Y downward, Z downward
sensorCoordinates(:,1) = -sensorCoordinates(:,1);
lateralSources(:,1) = -lateralSources(:,1);
medialSources(:,1) = -medialSources(:,1);
elseif strcmpi(kneeSide, "Left")
% Left knee: X positive rightward, Y downward, Z downward
% No inversion needed
else
error(‘Knee side must be either "Right" or "Left".’);
end
%% Plotting – 3D Plot
figure;
hold on;
% Plot sensor coordinates
scatter3(sensorCoordinates(:,1), sensorCoordinates(:,2), sensorCoordinates(:,3), …
80, ‘filled’, ‘MarkerFaceColor’, ‘b’);
% Add sensor name labels
for i = 1:length(sensorNames)
text(sensorCoordinates(i,1), sensorCoordinates(i,2), sensorCoordinates(i,3), …
[‘ ‘ char(sensorNames{i})], ‘FontSize’, 10, ‘Color’, ‘b’);
end
% Plot lateral sources
scatter3(lateralSources(:,1), lateralSources(:,2), lateralSources(:,3), …
60, ‘o’, ‘MarkerEdgeColor’, ‘r’, ‘DisplayName’, ‘Lateral Sources’);
% Plot medial sources
scatter3(medialSources(:,1), medialSources(:,2), medialSources(:,3), …
60, ‘s’, ‘MarkerEdgeColor’, ‘g’, ‘DisplayName’, ‘Medial Sources’);
%% Formatting for 3D plot
grid on;
xlabel(‘X-axis’);
ylabel(‘Y-axis’);
zlabel(‘Z-axis’);
title([‘3D Plot of Sensors and Sources (‘ kneeSide ‘ Knee)’]);
legend;
view(3);
hold off;
%% Plotting – 2D Plot (X vs Y)
figure;
hold on;
scatter(sensorCoordinates(:,1), sensorCoordinates(:,2), 80, ‘filled’, ‘b’);
for i = 1:length(sensorNames)
text(sensorCoordinates(i,1), sensorCoordinates(i,2), [‘ ‘ char(sensorNames{i})], ‘FontSize’, 10, ‘Color’, ‘b’);
end
scatter(lateralSources(:,1), lateralSources(:,2), 60, ‘ro’, ‘DisplayName’, ‘Lateral Sources’);
scatter(medialSources(:,1), medialSources(:,2), 60, ‘gs’, ‘DisplayName’, ‘Medial Sources’);
xlabel(‘X-axis’);
ylabel(‘Y-axis’);
title([‘2D Plot (X vs Y) – ‘ kneeSide ‘ Knee’]);
legend;
grid on;
hold off;
%% Plotting – 2D Plot (X vs Z)
figure;
hold on;
scatter(sensorCoordinates(:,1), sensorCoordinates(:,3), 80, ‘filled’, ‘b’);
for i = 1:length(sensorNames)
text(sensorCoordinates(i,1), sensorCoordinates(i,3), [‘ ‘ char(sensorNames{i})], ‘FontSize’, 10, ‘Color’, ‘b’);
end
scatter(lateralSources(:,1), lateralSources(:,3), 60, ‘ro’, ‘DisplayName’, ‘Lateral Sources’);
scatter(medialSources(:,1), medialSources(:,3), 60, ‘gs’, ‘DisplayName’, ‘Medial Sources’);
xlabel(‘X-axis’);
ylabel(‘Z-axis’);
title([‘2D Plot (X vs Z) – ‘ kneeSide ‘ Knee’]);
legend;
grid on;
hold off; The CSV file contains the following data:
Sensor names: sensorNames = data.Sensor(1:6,1)
Sensor coordinates: sensorCoordinates = data{1:6, 2:4}
Source number: (:,5)
Source coordinates: sourceCoordinates = data{:, 6:end}
I want to create a 3D plot in MATLAB that includes the following:
Plot the sensor names and their coordinates.
Plot the source coordinates. The source coordinates are categorized into two groups:
Medial: sourceCoordinates = data{7:end, 6:end}
Lateral: sourceCoordinates = data{1:6, 6:end}
3. Set the axis directions depending on the knee side (see figure. 1 below), using S2 as the reference sensor (0,0,0):
Figure.1
Right knee: X-axis positive leftward, Y-axis positive downward, Z-axis positive perpendicular to the depth of the plane.
Left knee: X-axis positive rightward, Y-axis positive downward, Z-axis positive perpendicular to the depth of the plane.
4. Generate three types of plots (similar to the figure.2):
A 3D plot with all axes.
A 2D plot of X vs. Y.
A 2D plot of X vs. Z.
5. Add a line (like the green line in the figure.2 below) that connects the medial and lateral sources. This line should represent the knee joint range in all axis directions.
Figure.2
Knee joint range determination table.
I would like to write a MATLAB script that reads the CSV file, extracts the relevant data, and generates the 3D and 2D plots including the above details.
I wrote the following code:
%% Read and Plot 3D/2D Data from CSV File
% Load the CSV file
filename = ‘3DPlot_KLII_Mori.csv’;
data = readtable(filename);
%% Extract Sensor and Source Data
sensorNames = data.Sensor(1:6, 1); % Sensor names
sensorCoordinates = data{1:6, 2:4}; % Sensor coordinates (X, Y, Z)
sourceNumbers = data{:, 5}; % Source numbers
sourceCoordinates = data{:, 6:end}; % All source coordinates
% Categorize source coordinates
lateralSources = data{1:6, 6:end}; % Lateral sources
medialSources = data{7:end, 6:end}; % Medial sources
%% User input for knee side
kneeSide = "Right"; % Change to "Left" if left knee
% Adjust axis directions based on knee side
if strcmpi(kneeSide, "Right")
% Right knee: X positive leftward, Y downward, Z downward
sensorCoordinates(:,1) = -sensorCoordinates(:,1);
lateralSources(:,1) = -lateralSources(:,1);
medialSources(:,1) = -medialSources(:,1);
elseif strcmpi(kneeSide, "Left")
% Left knee: X positive rightward, Y downward, Z downward
% No inversion needed
else
error(‘Knee side must be either "Right" or "Left".’);
end
%% Plotting – 3D Plot
figure;
hold on;
% Plot sensor coordinates
scatter3(sensorCoordinates(:,1), sensorCoordinates(:,2), sensorCoordinates(:,3), …
80, ‘filled’, ‘MarkerFaceColor’, ‘b’);
% Add sensor name labels
for i = 1:length(sensorNames)
text(sensorCoordinates(i,1), sensorCoordinates(i,2), sensorCoordinates(i,3), …
[‘ ‘ char(sensorNames{i})], ‘FontSize’, 10, ‘Color’, ‘b’);
end
% Plot lateral sources
scatter3(lateralSources(:,1), lateralSources(:,2), lateralSources(:,3), …
60, ‘o’, ‘MarkerEdgeColor’, ‘r’, ‘DisplayName’, ‘Lateral Sources’);
% Plot medial sources
scatter3(medialSources(:,1), medialSources(:,2), medialSources(:,3), …
60, ‘s’, ‘MarkerEdgeColor’, ‘g’, ‘DisplayName’, ‘Medial Sources’);
%% Formatting for 3D plot
grid on;
xlabel(‘X-axis’);
ylabel(‘Y-axis’);
zlabel(‘Z-axis’);
title([‘3D Plot of Sensors and Sources (‘ kneeSide ‘ Knee)’]);
legend;
view(3);
hold off;
%% Plotting – 2D Plot (X vs Y)
figure;
hold on;
scatter(sensorCoordinates(:,1), sensorCoordinates(:,2), 80, ‘filled’, ‘b’);
for i = 1:length(sensorNames)
text(sensorCoordinates(i,1), sensorCoordinates(i,2), [‘ ‘ char(sensorNames{i})], ‘FontSize’, 10, ‘Color’, ‘b’);
end
scatter(lateralSources(:,1), lateralSources(:,2), 60, ‘ro’, ‘DisplayName’, ‘Lateral Sources’);
scatter(medialSources(:,1), medialSources(:,2), 60, ‘gs’, ‘DisplayName’, ‘Medial Sources’);
xlabel(‘X-axis’);
ylabel(‘Y-axis’);
title([‘2D Plot (X vs Y) – ‘ kneeSide ‘ Knee’]);
legend;
grid on;
hold off;
%% Plotting – 2D Plot (X vs Z)
figure;
hold on;
scatter(sensorCoordinates(:,1), sensorCoordinates(:,3), 80, ‘filled’, ‘b’);
for i = 1:length(sensorNames)
text(sensorCoordinates(i,1), sensorCoordinates(i,3), [‘ ‘ char(sensorNames{i})], ‘FontSize’, 10, ‘Color’, ‘b’);
end
scatter(lateralSources(:,1), lateralSources(:,3), 60, ‘ro’, ‘DisplayName’, ‘Lateral Sources’);
scatter(medialSources(:,1), medialSources(:,3), 60, ‘gs’, ‘DisplayName’, ‘Medial Sources’);
xlabel(‘X-axis’);
ylabel(‘Z-axis’);
title([‘2D Plot (X vs Z) – ‘ kneeSide ‘ Knee’]);
legend;
grid on;
hold off; matlab, 3d-plot, customized axes MATLAB Answers — New Questions
MATLAB Dropout layer during prediciton
The Documentation for a Dropout layer states that:
"At prediction time the output of a dropout layer is equal to its input."
I assume this means that during prediction, there is no dropout.
Is there a method in MATLAB to enable Dropout during prediction time?The Documentation for a Dropout layer states that:
"At prediction time the output of a dropout layer is equal to its input."
I assume this means that during prediction, there is no dropout.
Is there a method in MATLAB to enable Dropout during prediction time? The Documentation for a Dropout layer states that:
"At prediction time the output of a dropout layer is equal to its input."
I assume this means that during prediction, there is no dropout.
Is there a method in MATLAB to enable Dropout during prediction time? deep-learing, neural network MATLAB Answers — New Questions
What is the MATLAB Package Manager? How do I download and install products with it?
What is the MATLAB Package Manager? How do I download and install products with it?What is the MATLAB Package Manager? How do I download and install products with it? What is the MATLAB Package Manager? How do I download and install products with it? MATLAB Answers — New Questions
C-Caller crash with Matlab 2025a
I have many models which uses C-Callers and they work properly in accelerator mode with matlab 2024b and previous.
With Matlab 2025a almost all these models crash when I run them. "Validate custom code" runs fine, but when I run the model it crash. In normal as it should be it doesn’t crash.
The issue is located into the C-caller of course, but I never had problems until R2025a.
Do you have similar issues? Any advices?
Many thanks in advanced.
DI have many models which uses C-Callers and they work properly in accelerator mode with matlab 2024b and previous.
With Matlab 2025a almost all these models crash when I run them. "Validate custom code" runs fine, but when I run the model it crash. In normal as it should be it doesn’t crash.
The issue is located into the C-caller of course, but I never had problems until R2025a.
Do you have similar issues? Any advices?
Many thanks in advanced.
D I have many models which uses C-Callers and they work properly in accelerator mode with matlab 2024b and previous.
With Matlab 2025a almost all these models crash when I run them. "Validate custom code" runs fine, but when I run the model it crash. In normal as it should be it doesn’t crash.
The issue is located into the C-caller of course, but I never had problems until R2025a.
Do you have similar issues? Any advices?
Many thanks in advanced.
D c-caller, simscape MATLAB Answers — New Questions
How does the Compare To Constant block in Simulink choose type of the Constant value, and what are the implications for fixed-point operations?
How can I detect and address questionable fixed-point operations in Compare To Constant block?
This example model generates code that does not function as intended. It appears that value 15 is cast to fixdt(1,8,-5) as sfix8_E5, and quantized to zero.How can I detect and address questionable fixed-point operations in Compare To Constant block?
This example model generates code that does not function as intended. It appears that value 15 is cast to fixdt(1,8,-5) as sfix8_E5, and quantized to zero. How can I detect and address questionable fixed-point operations in Compare To Constant block?
This example model generates code that does not function as intended. It appears that value 15 is cast to fixdt(1,8,-5) as sfix8_E5, and quantized to zero. fixed point, data type rules MATLAB Answers — New Questions
Problems with quiver plot
Hey!
I try to create a quiver plot with unequl axis length. I’ like to have the arrows the same length, which somehow does not want to work.
Any ideas?
Thanks!
%% system paramters
eta = .1;
mu = .1;
nu = 1;
gamma = 2;
%% dependent variables
roi = 2;
s = linspace(max([(1-roi)*s_0,0]),(1+roi)*s_0,10);
p = linspace(max([(1-roi)*p_0,0]),(1+roi)*p_0,10);
[s,p] = meshgrid(s,p);
%% gradient flow
v = s.*p.^gamma ./ (1+(1+s).*p.^gamma);
ds = -v + eta;
dp = mu*(v – nu*p);
mag = sqrt(ds.^2 + dp.^2);
arrow_scale = 3E-1;
norm_ds = arrow_scale*ds./mag;
norm_dp = arrow_scale*dp./mag;
%% plot
q = quiver(s,p,norm_ds,norm_dp,’Autoscale’,’off’, ‘Color’,.6*[1,1,1]);
q.ShowArrowHead = ‘off’;
q.Marker = ‘.’;Hey!
I try to create a quiver plot with unequl axis length. I’ like to have the arrows the same length, which somehow does not want to work.
Any ideas?
Thanks!
%% system paramters
eta = .1;
mu = .1;
nu = 1;
gamma = 2;
%% dependent variables
roi = 2;
s = linspace(max([(1-roi)*s_0,0]),(1+roi)*s_0,10);
p = linspace(max([(1-roi)*p_0,0]),(1+roi)*p_0,10);
[s,p] = meshgrid(s,p);
%% gradient flow
v = s.*p.^gamma ./ (1+(1+s).*p.^gamma);
ds = -v + eta;
dp = mu*(v – nu*p);
mag = sqrt(ds.^2 + dp.^2);
arrow_scale = 3E-1;
norm_ds = arrow_scale*ds./mag;
norm_dp = arrow_scale*dp./mag;
%% plot
q = quiver(s,p,norm_ds,norm_dp,’Autoscale’,’off’, ‘Color’,.6*[1,1,1]);
q.ShowArrowHead = ‘off’;
q.Marker = ‘.’; Hey!
I try to create a quiver plot with unequl axis length. I’ like to have the arrows the same length, which somehow does not want to work.
Any ideas?
Thanks!
%% system paramters
eta = .1;
mu = .1;
nu = 1;
gamma = 2;
%% dependent variables
roi = 2;
s = linspace(max([(1-roi)*s_0,0]),(1+roi)*s_0,10);
p = linspace(max([(1-roi)*p_0,0]),(1+roi)*p_0,10);
[s,p] = meshgrid(s,p);
%% gradient flow
v = s.*p.^gamma ./ (1+(1+s).*p.^gamma);
ds = -v + eta;
dp = mu*(v – nu*p);
mag = sqrt(ds.^2 + dp.^2);
arrow_scale = 3E-1;
norm_ds = arrow_scale*ds./mag;
norm_dp = arrow_scale*dp./mag;
%% plot
q = quiver(s,p,norm_ds,norm_dp,’Autoscale’,’off’, ‘Color’,.6*[1,1,1]);
q.ShowArrowHead = ‘off’;
q.Marker = ‘.’; quiver, plot MATLAB Answers — New Questions
Why Does Answers Run Code in 2025a But the Run Button, the “Executing In” Popup, and the “Ran In” Tag Still Show 2024b?
verver ver answers version MATLAB Answers — New Questions
Function requires a Toolbox for which you do not have a license
Up until today, I have been using my scripts without any issues. These scripts rely on a number of functions associated with certain toolboxes (for example, the tdfread function, which belongs to the Statistics and Machine Learning Toolbox). However, all of a sudden, MATLAB no longer allows me to run these scripts, as it tells me I do not have access to these functions.
It seems the reason is that I do not have a license for these toolboxes. Still, I have been able to use them without any problem until now, and my account is linked to an academic institution that supposedly has licenses for all of these toolboxes.
Could you please tell me what might be happening?Up until today, I have been using my scripts without any issues. These scripts rely on a number of functions associated with certain toolboxes (for example, the tdfread function, which belongs to the Statistics and Machine Learning Toolbox). However, all of a sudden, MATLAB no longer allows me to run these scripts, as it tells me I do not have access to these functions.
It seems the reason is that I do not have a license for these toolboxes. Still, I have been able to use them without any problem until now, and my account is linked to an academic institution that supposedly has licenses for all of these toolboxes.
Could you please tell me what might be happening? Up until today, I have been using my scripts without any issues. These scripts rely on a number of functions associated with certain toolboxes (for example, the tdfread function, which belongs to the Statistics and Machine Learning Toolbox). However, all of a sudden, MATLAB no longer allows me to run these scripts, as it tells me I do not have access to these functions.
It seems the reason is that I do not have a license for these toolboxes. Still, I have been able to use them without any problem until now, and my account is linked to an academic institution that supposedly has licenses for all of these toolboxes.
Could you please tell me what might be happening? license, toolkits, functions MATLAB Answers — New Questions
How can I change the fontsize of datatip box?
<</matlabcentral/answers/uploaded_files/108002/matlab.png>>
I mean the font size of x:5 and y:-12.38
Thanks in advance<</matlabcentral/answers/uploaded_files/108002/matlab.png>>
I mean the font size of x:5 and y:-12.38
Thanks in advance <</matlabcentral/answers/uploaded_files/108002/matlab.png>>
I mean the font size of x:5 and y:-12.38
Thanks in advance datatip, fontsize MATLAB Answers — New Questions
R2025a exportgraphics new behavior for PDF export
I use to export figure to PDF using the following code :
exportgraphics(fig, [ savepath ‘fig_name.pdf’], ‘ContentType’, ‘vector’);
It contains both plots and imagesc in subplots.
In Matlab R2024b, the exported PDF would look smooth even zooming in -> vector graphic confirmed. Or good enough let’s say: I’ve heard that imagesc figures can’t be vectorized in a proper way anyway.
In Matlab R2025a, the plots are ok, the imagesc are very blured, even if I specify dpi = 600 in the exportgraphic function.
So I’m guessing the behaviour of that function have changed.
Anyone has any input about this ?
How can I have the same result as in R2024b in R2025a is my question.I use to export figure to PDF using the following code :
exportgraphics(fig, [ savepath ‘fig_name.pdf’], ‘ContentType’, ‘vector’);
It contains both plots and imagesc in subplots.
In Matlab R2024b, the exported PDF would look smooth even zooming in -> vector graphic confirmed. Or good enough let’s say: I’ve heard that imagesc figures can’t be vectorized in a proper way anyway.
In Matlab R2025a, the plots are ok, the imagesc are very blured, even if I specify dpi = 600 in the exportgraphic function.
So I’m guessing the behaviour of that function have changed.
Anyone has any input about this ?
How can I have the same result as in R2024b in R2025a is my question. I use to export figure to PDF using the following code :
exportgraphics(fig, [ savepath ‘fig_name.pdf’], ‘ContentType’, ‘vector’);
It contains both plots and imagesc in subplots.
In Matlab R2024b, the exported PDF would look smooth even zooming in -> vector graphic confirmed. Or good enough let’s say: I’ve heard that imagesc figures can’t be vectorized in a proper way anyway.
In Matlab R2025a, the plots are ok, the imagesc are very blured, even if I specify dpi = 600 in the exportgraphic function.
So I’m guessing the behaviour of that function have changed.
Anyone has any input about this ?
How can I have the same result as in R2024b in R2025a is my question. exportgraphic, pdf, r2025a MATLAB Answers — New Questions
making a custom way to train CNNs, and I am noticing that avgpool is SIGNIFICANTLY faster than maxpool in forward and backwards passes…
I’m designing a custom training procedure for a CNN that is different from backpropagation in that I use manual update rules for layers or sets of layers. I’m studying my gradient for two types of layers: “conv + actfun + maxpool”, and “conv + actfun + avgpool”, which are identical layers except the last action is a different pooling type.
I compared the two layer types with identical data dimension sizes to see the time differences between maxpool and avgpool, both in the forward pass and the backwards pass of the pooling layers. All other steps in calculating the gradient were exactly the same between the two layers, and showed the same time costs in the two layers. But when looking at time costs specifically of the pooling operations’ forward and backwards passes, I get significantly different times (average of 5000 runs of the gradient, each measurement is in milliseconds):
gradient step | AvgPool | MaxPool | Difference
————————–|———|———|———-
pooling (forward pass) | 0.4165 | 38.6316 | +38.2151
unpooling (backward pass) | 9.9468 | 46.1667 | +36.2199
For reference, all my data arrays are dlarrays on the GPU (gpuArrays in dlarrays), all single precision, and the pooling operations convert 32 by 32 feature maps (across 2 channels and 16384 batch size) to 16 by 16 feature maps (of same # channels and batch size), so just a 2 by 2 pooling operation.
You can see here that the maxpool forward pass (using “maxpool” function) is about 92 times slower than the avgpool forward pass (using “avgpool”), and the maxpool backward pass (using “maxunpool”) is about 4.6 times slower than the avgpool backward pass (using a custom “avgunpool” function that Anthropic’s Claude had to create for me, since matlab has no “avgunpool”).
These results are extremely suspect to me. For the forwards pass, comparing matlab’s built in "maxpool" to built in "avgpool" functions gives a 92x difference, but searching online people seem to instead claim that training max pooling is supposed to be faster than avg pooling, which contradicts the results here.
For simplicity, see the code example below that runs just "maxpool" and "avgpool" only (no other functions) and compares their times:
function analyze_pooling_timing()
% GPU setup
g = gpuDevice();
fprintf(‘GPU: %sn’, g.Name);
% Parameters matching your test
H_in = 32; W_in = 32; C_in = 3; C_out = 2;
N = 16384; % batch size. Try N = 32 small or N = 16384 big
kH = 3; kW = 3;
pool_params.pool_size = [2, 2];
pool_params.pool_stride = [2, 2];
pool_params.pool_padding = 0;
conv_params.stride = [1, 1];
conv_params.padding = ‘same’;
conv_params.dilation = [1, 1];
% Initialize data
Wj = dlarray(gpuArray(single(randn(kH, kW, C_in, C_out) * 0.01)), ‘SSCU’);
Bj = dlarray(gpuArray(single(zeros(C_out, 1))), ‘C’);
Fjmin1 = dlarray(gpuArray(single(randn(H_in, W_in, C_in, N))), ‘SSCB’);
% Number of iterations for averaging
num_iter = 100;
fprintf(‘Running %d iterations for each timing measurement…nn’, num_iter);
%% setup everything in forward pass before the pooling:
% Forward convolution
Sj = dlconv(Fjmin1, Wj, Bj, …
‘Stride’, conv_params.stride, …
‘Padding’, conv_params.padding, …
‘DilationFactor’, conv_params.dilation);
% activation function (and derivative)
Oj = max(Sj, 0); Fprimej = sign(Oj);
%% Time AVERAGE POOLING
fprintf(‘=== AVERAGE POOLING (conv_af_ap) ===n’);
times_ap = struct();
for iter = 1:num_iter
% Average pooling
tic;
Oj_pooled = avgpool(Oj, pool_params.pool_size, …
‘Stride’, pool_params.pool_stride, …
‘Padding’, pool_params.pool_padding);
wait(g);
times_ap.pooling(iter) = toc;
end
%% Time MAX POOLING
fprintf(‘n=== MAX POOLING (conv_af_mp) ===n’);
times_mp = struct();
for iter = 1:num_iter
% Max pooling with indices
tic;
[Oj_pooled, max_indices] = maxpool(Oj, pool_params.pool_size, …
‘Stride’, pool_params.pool_stride, …
‘Padding’, pool_params.pool_padding);
wait(g);
times_mp.pooling(iter) = toc;
end
%% Compute statistics and display results
fprintf(‘n=== TIMING RESULTS (milliseconds) ===n’);
fprintf(‘%-25s %12s %12s %12sn’, ‘Step’, ‘AvgPool’, ‘MaxPool’, ‘Difference’);
fprintf(‘%sn’, repmat(‘-‘, 1, 65));
steps_common = { ‘pooling’};
total_ap = 0;
total_mp = 0;
for i = 1:length(steps_common)
step = steps_common{i};
if isfield(times_ap, step) && isfield(times_mp, step)
mean_ap = mean(times_ap.(step)) * 1000; % times 1000 to convert seconds to milliseconds
mean_mp = mean(times_mp.(step)) * 1000; % times 1000 to convert seconds to milliseconds
total_ap = total_ap + mean_ap;
total_mp = total_mp + mean_mp;
diff = mean_mp – mean_ap;
fprintf(‘%-25s %12.4f %12.4f %+12.4fn’, step, mean_ap, mean_mp, diff);
end
end
fprintf(‘%sn’, repmat(‘-‘, 1, 65));
%fprintf(‘%-25s %12.4f %12.4f %+12.4fn’, ‘TOTAL’, total_ap, total_mp, total_mp – total_ap);
fprintf(‘%-25s %12s %12s %12.2fxn’, ‘Speedup’, ”, ”, total_mp/total_ap);
end
Now you can see one main difference between my calling of maxpool and avgpool: for avgpool I only have 1 output (the pooled values), but with maxpool I have 2 outputs (the pooled values, and the index locations of these max values).
This is important because if I replaced the call to maxpool with only requesting the pooled values (1 output), maxpool is faster as expected:
>> analyze_pooling_timing
GPU: NVIDIA GeForce RTX 5080
Running 1000 iterations for each timing measurement…
=== AVERAGE POOLING (conv_af_ap) ===
=== MAX POOLING (conv_af_mp) ===
=== TIMING RESULTS (milliseconds) ===
Step AvgPool MaxPool Difference
—————————————————————–
pooling 0.4358 0.2330 -0.2028
—————————————————————–
max/avg 0.53x
>>
However if I call maxpool like here with 2 outputs (pooled values and indices), or with 3 outputs (pooled values, indices, and inputSize), this is where maxpool is extremely slow:
>> analyze_pooling_timing
GPU: NVIDIA GeForce RTX 5080
Running 1000 iterations for each timing measurement…
=== AVERAGE POOLING (conv_af_ap) ===
=== MAX POOLING (conv_af_mp) ===
=== TIMING RESULTS (milliseconds) ===
Step AvgPool MaxPool Difference
—————————————————————–
pooling 0.4153 38.9818 +38.5665
—————————————————————–
max/avg 93.86x
>>
So it appears that this is the reason why maxpool is so much slower: requesting the maxpool function to also output the indices leads to a massive slowdown.
Unfortunately, the indices are needed to later differentiate (backwards pass) the maxpool layer… so I need the indices…
I’d assume that whenever someone wants to train a CNN in matlab using a maxpool layer, they would have to call maxpool with indices, and thus I’d expect a similar slowdown…
Can anyone here comment on this? My application needs me to train maxpool layers, so I need to both forward pass and backwards pass through them, thus I need these indices. But it appears that matlab’s version of maxpool may not be the best implementation of a maxpool operation… maybe some inefficient processes regarding obtaining the indices?I’m designing a custom training procedure for a CNN that is different from backpropagation in that I use manual update rules for layers or sets of layers. I’m studying my gradient for two types of layers: “conv + actfun + maxpool”, and “conv + actfun + avgpool”, which are identical layers except the last action is a different pooling type.
I compared the two layer types with identical data dimension sizes to see the time differences between maxpool and avgpool, both in the forward pass and the backwards pass of the pooling layers. All other steps in calculating the gradient were exactly the same between the two layers, and showed the same time costs in the two layers. But when looking at time costs specifically of the pooling operations’ forward and backwards passes, I get significantly different times (average of 5000 runs of the gradient, each measurement is in milliseconds):
gradient step | AvgPool | MaxPool | Difference
————————–|———|———|———-
pooling (forward pass) | 0.4165 | 38.6316 | +38.2151
unpooling (backward pass) | 9.9468 | 46.1667 | +36.2199
For reference, all my data arrays are dlarrays on the GPU (gpuArrays in dlarrays), all single precision, and the pooling operations convert 32 by 32 feature maps (across 2 channels and 16384 batch size) to 16 by 16 feature maps (of same # channels and batch size), so just a 2 by 2 pooling operation.
You can see here that the maxpool forward pass (using “maxpool” function) is about 92 times slower than the avgpool forward pass (using “avgpool”), and the maxpool backward pass (using “maxunpool”) is about 4.6 times slower than the avgpool backward pass (using a custom “avgunpool” function that Anthropic’s Claude had to create for me, since matlab has no “avgunpool”).
These results are extremely suspect to me. For the forwards pass, comparing matlab’s built in "maxpool" to built in "avgpool" functions gives a 92x difference, but searching online people seem to instead claim that training max pooling is supposed to be faster than avg pooling, which contradicts the results here.
For simplicity, see the code example below that runs just "maxpool" and "avgpool" only (no other functions) and compares their times:
function analyze_pooling_timing()
% GPU setup
g = gpuDevice();
fprintf(‘GPU: %sn’, g.Name);
% Parameters matching your test
H_in = 32; W_in = 32; C_in = 3; C_out = 2;
N = 16384; % batch size. Try N = 32 small or N = 16384 big
kH = 3; kW = 3;
pool_params.pool_size = [2, 2];
pool_params.pool_stride = [2, 2];
pool_params.pool_padding = 0;
conv_params.stride = [1, 1];
conv_params.padding = ‘same’;
conv_params.dilation = [1, 1];
% Initialize data
Wj = dlarray(gpuArray(single(randn(kH, kW, C_in, C_out) * 0.01)), ‘SSCU’);
Bj = dlarray(gpuArray(single(zeros(C_out, 1))), ‘C’);
Fjmin1 = dlarray(gpuArray(single(randn(H_in, W_in, C_in, N))), ‘SSCB’);
% Number of iterations for averaging
num_iter = 100;
fprintf(‘Running %d iterations for each timing measurement…nn’, num_iter);
%% setup everything in forward pass before the pooling:
% Forward convolution
Sj = dlconv(Fjmin1, Wj, Bj, …
‘Stride’, conv_params.stride, …
‘Padding’, conv_params.padding, …
‘DilationFactor’, conv_params.dilation);
% activation function (and derivative)
Oj = max(Sj, 0); Fprimej = sign(Oj);
%% Time AVERAGE POOLING
fprintf(‘=== AVERAGE POOLING (conv_af_ap) ===n’);
times_ap = struct();
for iter = 1:num_iter
% Average pooling
tic;
Oj_pooled = avgpool(Oj, pool_params.pool_size, …
‘Stride’, pool_params.pool_stride, …
‘Padding’, pool_params.pool_padding);
wait(g);
times_ap.pooling(iter) = toc;
end
%% Time MAX POOLING
fprintf(‘n=== MAX POOLING (conv_af_mp) ===n’);
times_mp = struct();
for iter = 1:num_iter
% Max pooling with indices
tic;
[Oj_pooled, max_indices] = maxpool(Oj, pool_params.pool_size, …
‘Stride’, pool_params.pool_stride, …
‘Padding’, pool_params.pool_padding);
wait(g);
times_mp.pooling(iter) = toc;
end
%% Compute statistics and display results
fprintf(‘n=== TIMING RESULTS (milliseconds) ===n’);
fprintf(‘%-25s %12s %12s %12sn’, ‘Step’, ‘AvgPool’, ‘MaxPool’, ‘Difference’);
fprintf(‘%sn’, repmat(‘-‘, 1, 65));
steps_common = { ‘pooling’};
total_ap = 0;
total_mp = 0;
for i = 1:length(steps_common)
step = steps_common{i};
if isfield(times_ap, step) && isfield(times_mp, step)
mean_ap = mean(times_ap.(step)) * 1000; % times 1000 to convert seconds to milliseconds
mean_mp = mean(times_mp.(step)) * 1000; % times 1000 to convert seconds to milliseconds
total_ap = total_ap + mean_ap;
total_mp = total_mp + mean_mp;
diff = mean_mp – mean_ap;
fprintf(‘%-25s %12.4f %12.4f %+12.4fn’, step, mean_ap, mean_mp, diff);
end
end
fprintf(‘%sn’, repmat(‘-‘, 1, 65));
%fprintf(‘%-25s %12.4f %12.4f %+12.4fn’, ‘TOTAL’, total_ap, total_mp, total_mp – total_ap);
fprintf(‘%-25s %12s %12s %12.2fxn’, ‘Speedup’, ”, ”, total_mp/total_ap);
end
Now you can see one main difference between my calling of maxpool and avgpool: for avgpool I only have 1 output (the pooled values), but with maxpool I have 2 outputs (the pooled values, and the index locations of these max values).
This is important because if I replaced the call to maxpool with only requesting the pooled values (1 output), maxpool is faster as expected:
>> analyze_pooling_timing
GPU: NVIDIA GeForce RTX 5080
Running 1000 iterations for each timing measurement…
=== AVERAGE POOLING (conv_af_ap) ===
=== MAX POOLING (conv_af_mp) ===
=== TIMING RESULTS (milliseconds) ===
Step AvgPool MaxPool Difference
—————————————————————–
pooling 0.4358 0.2330 -0.2028
—————————————————————–
max/avg 0.53x
>>
However if I call maxpool like here with 2 outputs (pooled values and indices), or with 3 outputs (pooled values, indices, and inputSize), this is where maxpool is extremely slow:
>> analyze_pooling_timing
GPU: NVIDIA GeForce RTX 5080
Running 1000 iterations for each timing measurement…
=== AVERAGE POOLING (conv_af_ap) ===
=== MAX POOLING (conv_af_mp) ===
=== TIMING RESULTS (milliseconds) ===
Step AvgPool MaxPool Difference
—————————————————————–
pooling 0.4153 38.9818 +38.5665
—————————————————————–
max/avg 93.86x
>>
So it appears that this is the reason why maxpool is so much slower: requesting the maxpool function to also output the indices leads to a massive slowdown.
Unfortunately, the indices are needed to later differentiate (backwards pass) the maxpool layer… so I need the indices…
I’d assume that whenever someone wants to train a CNN in matlab using a maxpool layer, they would have to call maxpool with indices, and thus I’d expect a similar slowdown…
Can anyone here comment on this? My application needs me to train maxpool layers, so I need to both forward pass and backwards pass through them, thus I need these indices. But it appears that matlab’s version of maxpool may not be the best implementation of a maxpool operation… maybe some inefficient processes regarding obtaining the indices? I’m designing a custom training procedure for a CNN that is different from backpropagation in that I use manual update rules for layers or sets of layers. I’m studying my gradient for two types of layers: “conv + actfun + maxpool”, and “conv + actfun + avgpool”, which are identical layers except the last action is a different pooling type.
I compared the two layer types with identical data dimension sizes to see the time differences between maxpool and avgpool, both in the forward pass and the backwards pass of the pooling layers. All other steps in calculating the gradient were exactly the same between the two layers, and showed the same time costs in the two layers. But when looking at time costs specifically of the pooling operations’ forward and backwards passes, I get significantly different times (average of 5000 runs of the gradient, each measurement is in milliseconds):
gradient step | AvgPool | MaxPool | Difference
————————–|———|———|———-
pooling (forward pass) | 0.4165 | 38.6316 | +38.2151
unpooling (backward pass) | 9.9468 | 46.1667 | +36.2199
For reference, all my data arrays are dlarrays on the GPU (gpuArrays in dlarrays), all single precision, and the pooling operations convert 32 by 32 feature maps (across 2 channels and 16384 batch size) to 16 by 16 feature maps (of same # channels and batch size), so just a 2 by 2 pooling operation.
You can see here that the maxpool forward pass (using “maxpool” function) is about 92 times slower than the avgpool forward pass (using “avgpool”), and the maxpool backward pass (using “maxunpool”) is about 4.6 times slower than the avgpool backward pass (using a custom “avgunpool” function that Anthropic’s Claude had to create for me, since matlab has no “avgunpool”).
These results are extremely suspect to me. For the forwards pass, comparing matlab’s built in "maxpool" to built in "avgpool" functions gives a 92x difference, but searching online people seem to instead claim that training max pooling is supposed to be faster than avg pooling, which contradicts the results here.
For simplicity, see the code example below that runs just "maxpool" and "avgpool" only (no other functions) and compares their times:
function analyze_pooling_timing()
% GPU setup
g = gpuDevice();
fprintf(‘GPU: %sn’, g.Name);
% Parameters matching your test
H_in = 32; W_in = 32; C_in = 3; C_out = 2;
N = 16384; % batch size. Try N = 32 small or N = 16384 big
kH = 3; kW = 3;
pool_params.pool_size = [2, 2];
pool_params.pool_stride = [2, 2];
pool_params.pool_padding = 0;
conv_params.stride = [1, 1];
conv_params.padding = ‘same’;
conv_params.dilation = [1, 1];
% Initialize data
Wj = dlarray(gpuArray(single(randn(kH, kW, C_in, C_out) * 0.01)), ‘SSCU’);
Bj = dlarray(gpuArray(single(zeros(C_out, 1))), ‘C’);
Fjmin1 = dlarray(gpuArray(single(randn(H_in, W_in, C_in, N))), ‘SSCB’);
% Number of iterations for averaging
num_iter = 100;
fprintf(‘Running %d iterations for each timing measurement…nn’, num_iter);
%% setup everything in forward pass before the pooling:
% Forward convolution
Sj = dlconv(Fjmin1, Wj, Bj, …
‘Stride’, conv_params.stride, …
‘Padding’, conv_params.padding, …
‘DilationFactor’, conv_params.dilation);
% activation function (and derivative)
Oj = max(Sj, 0); Fprimej = sign(Oj);
%% Time AVERAGE POOLING
fprintf(‘=== AVERAGE POOLING (conv_af_ap) ===n’);
times_ap = struct();
for iter = 1:num_iter
% Average pooling
tic;
Oj_pooled = avgpool(Oj, pool_params.pool_size, …
‘Stride’, pool_params.pool_stride, …
‘Padding’, pool_params.pool_padding);
wait(g);
times_ap.pooling(iter) = toc;
end
%% Time MAX POOLING
fprintf(‘n=== MAX POOLING (conv_af_mp) ===n’);
times_mp = struct();
for iter = 1:num_iter
% Max pooling with indices
tic;
[Oj_pooled, max_indices] = maxpool(Oj, pool_params.pool_size, …
‘Stride’, pool_params.pool_stride, …
‘Padding’, pool_params.pool_padding);
wait(g);
times_mp.pooling(iter) = toc;
end
%% Compute statistics and display results
fprintf(‘n=== TIMING RESULTS (milliseconds) ===n’);
fprintf(‘%-25s %12s %12s %12sn’, ‘Step’, ‘AvgPool’, ‘MaxPool’, ‘Difference’);
fprintf(‘%sn’, repmat(‘-‘, 1, 65));
steps_common = { ‘pooling’};
total_ap = 0;
total_mp = 0;
for i = 1:length(steps_common)
step = steps_common{i};
if isfield(times_ap, step) && isfield(times_mp, step)
mean_ap = mean(times_ap.(step)) * 1000; % times 1000 to convert seconds to milliseconds
mean_mp = mean(times_mp.(step)) * 1000; % times 1000 to convert seconds to milliseconds
total_ap = total_ap + mean_ap;
total_mp = total_mp + mean_mp;
diff = mean_mp – mean_ap;
fprintf(‘%-25s %12.4f %12.4f %+12.4fn’, step, mean_ap, mean_mp, diff);
end
end
fprintf(‘%sn’, repmat(‘-‘, 1, 65));
%fprintf(‘%-25s %12.4f %12.4f %+12.4fn’, ‘TOTAL’, total_ap, total_mp, total_mp – total_ap);
fprintf(‘%-25s %12s %12s %12.2fxn’, ‘Speedup’, ”, ”, total_mp/total_ap);
end
Now you can see one main difference between my calling of maxpool and avgpool: for avgpool I only have 1 output (the pooled values), but with maxpool I have 2 outputs (the pooled values, and the index locations of these max values).
This is important because if I replaced the call to maxpool with only requesting the pooled values (1 output), maxpool is faster as expected:
>> analyze_pooling_timing
GPU: NVIDIA GeForce RTX 5080
Running 1000 iterations for each timing measurement…
=== AVERAGE POOLING (conv_af_ap) ===
=== MAX POOLING (conv_af_mp) ===
=== TIMING RESULTS (milliseconds) ===
Step AvgPool MaxPool Difference
—————————————————————–
pooling 0.4358 0.2330 -0.2028
—————————————————————–
max/avg 0.53x
>>
However if I call maxpool like here with 2 outputs (pooled values and indices), or with 3 outputs (pooled values, indices, and inputSize), this is where maxpool is extremely slow:
>> analyze_pooling_timing
GPU: NVIDIA GeForce RTX 5080
Running 1000 iterations for each timing measurement…
=== AVERAGE POOLING (conv_af_ap) ===
=== MAX POOLING (conv_af_mp) ===
=== TIMING RESULTS (milliseconds) ===
Step AvgPool MaxPool Difference
—————————————————————–
pooling 0.4153 38.9818 +38.5665
—————————————————————–
max/avg 93.86x
>>
So it appears that this is the reason why maxpool is so much slower: requesting the maxpool function to also output the indices leads to a massive slowdown.
Unfortunately, the indices are needed to later differentiate (backwards pass) the maxpool layer… so I need the indices…
I’d assume that whenever someone wants to train a CNN in matlab using a maxpool layer, they would have to call maxpool with indices, and thus I’d expect a similar slowdown…
Can anyone here comment on this? My application needs me to train maxpool layers, so I need to both forward pass and backwards pass through them, thus I need these indices. But it appears that matlab’s version of maxpool may not be the best implementation of a maxpool operation… maybe some inefficient processes regarding obtaining the indices? deep learning, maxpool, avgpool, indexing MATLAB Answers — New Questions