Author: PuTI
How to make Rounded Edges of rectangle corners with polyshape function ?
hello, everybody
I would like to make the rounded rectangle and I would like them to translated and rotated.
First I tried with rectangle function using ‘Curvature’ of 1. then I can make the rounded rectangle.
However, it is not possible for them to translated and rotated.
Therefore, I made the rectangle with polyshape function. and it is okay for them to translated and rotated.
However, i do not know how I can make them to have rounded edges.
Could you please helpe me how to make them to rounded edges with polyshape function?
clear; close all; clc;
figure(1); hold on; axis equal
% Before translating and rotating
rectangle(‘Position’,[-14.1276, 226.1976, 6.5929, 9.4184],’FaceColor’,’r’,’Curvature’,1)
% After translating and rotating
% translate and rotate polygon
x = [-14.1276; -14.1276+6.5929; -14.1276+6.5929; -14.1276];
y = [226.1976; 226.1976; 226.1976+9.4184; 226.1976+9.4184];
p = [x,y];
pgon = polyshape(p);
pgon = translate(pgon,50,-75);
pgon = rotate(pgon,18,[57, 349]);
plot(pgon,’FaceColor’,’red’,’FaceAlpha’,1)
% object by rectangle function can not translated and rotated.hello, everybody
I would like to make the rounded rectangle and I would like them to translated and rotated.
First I tried with rectangle function using ‘Curvature’ of 1. then I can make the rounded rectangle.
However, it is not possible for them to translated and rotated.
Therefore, I made the rectangle with polyshape function. and it is okay for them to translated and rotated.
However, i do not know how I can make them to have rounded edges.
Could you please helpe me how to make them to rounded edges with polyshape function?
clear; close all; clc;
figure(1); hold on; axis equal
% Before translating and rotating
rectangle(‘Position’,[-14.1276, 226.1976, 6.5929, 9.4184],’FaceColor’,’r’,’Curvature’,1)
% After translating and rotating
% translate and rotate polygon
x = [-14.1276; -14.1276+6.5929; -14.1276+6.5929; -14.1276];
y = [226.1976; 226.1976; 226.1976+9.4184; 226.1976+9.4184];
p = [x,y];
pgon = polyshape(p);
pgon = translate(pgon,50,-75);
pgon = rotate(pgon,18,[57, 349]);
plot(pgon,’FaceColor’,’red’,’FaceAlpha’,1)
% object by rectangle function can not translated and rotated. hello, everybody
I would like to make the rounded rectangle and I would like them to translated and rotated.
First I tried with rectangle function using ‘Curvature’ of 1. then I can make the rounded rectangle.
However, it is not possible for them to translated and rotated.
Therefore, I made the rectangle with polyshape function. and it is okay for them to translated and rotated.
However, i do not know how I can make them to have rounded edges.
Could you please helpe me how to make them to rounded edges with polyshape function?
clear; close all; clc;
figure(1); hold on; axis equal
% Before translating and rotating
rectangle(‘Position’,[-14.1276, 226.1976, 6.5929, 9.4184],’FaceColor’,’r’,’Curvature’,1)
% After translating and rotating
% translate and rotate polygon
x = [-14.1276; -14.1276+6.5929; -14.1276+6.5929; -14.1276];
y = [226.1976; 226.1976; 226.1976+9.4184; 226.1976+9.4184];
p = [x,y];
pgon = polyshape(p);
pgon = translate(pgon,50,-75);
pgon = rotate(pgon,18,[57, 349]);
plot(pgon,’FaceColor’,’red’,’FaceAlpha’,1)
% object by rectangle function can not translated and rotated. curvature MATLAB Answers — New Questions
Please help me to run this code
function sol= proj
clc;clf;clear;
%Relation of base fluid
rhof=997.1*10^-3;kf=0.613*10^5;cpf=4179*10^4;muf=10^-3*10;
alfaf=kf/(rhof*cpf);
bef=21*10^-5;
ky=muf/rhof;
disp(‘ky’);disp((muf/rhof));
%sigf=0.05*10^-8;
%Ag
ph1=0.01;
rho1=10500*10^-3;
cp1=235*10^4;
k1=429*10^5;be1=21*10^-5;
%sig1=0.74*10^-2;
%copper
ph2=0.01;
rho2=8933*10^-3;
cp2=385*10^4;
k2=400*10^5;
%sig2=5.96*10^-1;
be2=1.67*10^-5;
%Alumina
ph3=0.01;
rho3=3970*10^-3;
cp3=765*10^4;
k3=40*10^5;
be3=0.85*10^-5;
%sig3=3.5*10^-1;
%Relation of ternary hyprid
kn=kf*((k3+2*kf-2*ph3*(kf-k3))/(k3+2*kf+ph3*(kf-k3)));
kh=kn*((k2+2*kn-2*ph2*(kn-k2))/(k2+2*kn+ph2*(kn-k2)));
kt=kh*((k1+2*kh-2*ph1*(kh-k1))/(k1+2*kh+ph1*(kh-k1)));
mut= muf/((1-ph1)^2.5*(1-ph2)^2.5*(1-ph3)^2.5);
rhot=(1-ph1)*((1-ph2)*((1-ph3)+ph3*(rho3/rhof))+ph2*(rho2/rhof))+ph1*(rho1/rhof);
%vt=rhot*cpt
vt =(1-ph1)*((1-ph2)*((1-ph3)+ph3*((rho3*cp3)/(rhof*cpf)))+ph2*((rho2*cp2)/(rhof*cpf)))+ph1*((rho1*cp1)/(rhof*cpf));
%disp(‘vt’);disp(vt);
%vb=rho*betb
vb =(1-ph1)*((1-ph2)*((1-ph3)+ph3*((rho3*be3)/(rhof*bef)))+ph2*((rho2*be2)/(rhof*bef)))+ph1*((rho1*be1)/(rhof*bef));
%disp(‘vb’);disp(vb);disp(ky);
myLegend1 = {};myLegend2 = {};
%for i =1:numel(rr)
rr = [0 1 2];
numGr = numel(rr);
m = linspace(0,1);
a=-0.001;b=0.0001;p=-0.15/((1-0.01)*(mut/muf)*(rhof/rhot));
Ec=0.5;
gamma=pi/4;
prf=6.9;Rd=0.5;
Tw=273+50;Ti=273+27;deltaT=Tw-Ti;
disp(‘coe’);disp((mut/muf)*(rhof/rhot));
Lf=rhof*kf;
y0 = [1,0,1,0,0,1,0,1];options =bvpset(‘stats’,’on’,’RelTol’,1e-5);
%solinit = bvpinit(m,y0);
% sol= bvp4c(@projfun,@projbc,solinit,options);
Z = zeros(numGr, length(m));
for i = 1:numGr
Gr= rr(i);
solinit = bvpinit(m, y0);
sol = bvp4c(@projfun, @projbc, solinit, options);
Z(i, 🙂 = deval(sol,m,1); % Store the z-axis data
end
[X, Y] = meshgrid(m, rr);
figure;
surf(X, Y, Z);
xlabel(‘x’);
ylabel(‘Prf’);
zlabel(‘Solution y(6,:)’);
title(‘Surface Plot of Solution’);
grid on;
function dy= projfun(~,y)
dy= zeros(8,1);
% alignComments
E = y(1);
dE = y(2);
F = y(3);
dF= y(4);
w = y(5);
dw=y(6);
t = y(7);
dt = y(8);
dy(1) = dE;
dy(2) = (((rhot/mut)*(a*(muf/rhof)^0.5*(E*F+E^2)+a*(muf/rhof)*w*dE-(mut/muf)*(rhof/rhot)*p*(1-0.01)*E+Gr*a*(muf/rhof)*sin(gamma)*(vb/(rhof*bef))*t)));
dy(3) = dF;
dy(4) = (((rhot/mut)*(b*(muf/rhof)^0.5*(F^2+F*E)+(muf/rhof)*b^0.5*a^(1.5)*dF)));
dy(5) =-(a*F+b*E);
dy(6) = (((rhot/mut)*((muf/rhof)^0.5*w*dw+Gr*b*(muf/rhof)*cos(gamma)*(vb/(rhof*bef))*t)));
dy(7) = dt;
dy(8)=prf*(1/(kt/kf))*(1/(1+((prf*Rd)/((kt/kf)))))*((vt/(rhof*cpf))*(muf/rhof)^0.5*w*dt-(mut/muf)*Ec*1*dw^2) ;
end
end
function res= projbc(ya,yb)
res= [ya(1)+1;
ya(3)-1;
ya(5);
ya(6);
ya(7)-1-(1/0.9)*ya(8);
yb(1)-0.01;
yb(3);
yb(7);
% yb(7);
];
endfunction sol= proj
clc;clf;clear;
%Relation of base fluid
rhof=997.1*10^-3;kf=0.613*10^5;cpf=4179*10^4;muf=10^-3*10;
alfaf=kf/(rhof*cpf);
bef=21*10^-5;
ky=muf/rhof;
disp(‘ky’);disp((muf/rhof));
%sigf=0.05*10^-8;
%Ag
ph1=0.01;
rho1=10500*10^-3;
cp1=235*10^4;
k1=429*10^5;be1=21*10^-5;
%sig1=0.74*10^-2;
%copper
ph2=0.01;
rho2=8933*10^-3;
cp2=385*10^4;
k2=400*10^5;
%sig2=5.96*10^-1;
be2=1.67*10^-5;
%Alumina
ph3=0.01;
rho3=3970*10^-3;
cp3=765*10^4;
k3=40*10^5;
be3=0.85*10^-5;
%sig3=3.5*10^-1;
%Relation of ternary hyprid
kn=kf*((k3+2*kf-2*ph3*(kf-k3))/(k3+2*kf+ph3*(kf-k3)));
kh=kn*((k2+2*kn-2*ph2*(kn-k2))/(k2+2*kn+ph2*(kn-k2)));
kt=kh*((k1+2*kh-2*ph1*(kh-k1))/(k1+2*kh+ph1*(kh-k1)));
mut= muf/((1-ph1)^2.5*(1-ph2)^2.5*(1-ph3)^2.5);
rhot=(1-ph1)*((1-ph2)*((1-ph3)+ph3*(rho3/rhof))+ph2*(rho2/rhof))+ph1*(rho1/rhof);
%vt=rhot*cpt
vt =(1-ph1)*((1-ph2)*((1-ph3)+ph3*((rho3*cp3)/(rhof*cpf)))+ph2*((rho2*cp2)/(rhof*cpf)))+ph1*((rho1*cp1)/(rhof*cpf));
%disp(‘vt’);disp(vt);
%vb=rho*betb
vb =(1-ph1)*((1-ph2)*((1-ph3)+ph3*((rho3*be3)/(rhof*bef)))+ph2*((rho2*be2)/(rhof*bef)))+ph1*((rho1*be1)/(rhof*bef));
%disp(‘vb’);disp(vb);disp(ky);
myLegend1 = {};myLegend2 = {};
%for i =1:numel(rr)
rr = [0 1 2];
numGr = numel(rr);
m = linspace(0,1);
a=-0.001;b=0.0001;p=-0.15/((1-0.01)*(mut/muf)*(rhof/rhot));
Ec=0.5;
gamma=pi/4;
prf=6.9;Rd=0.5;
Tw=273+50;Ti=273+27;deltaT=Tw-Ti;
disp(‘coe’);disp((mut/muf)*(rhof/rhot));
Lf=rhof*kf;
y0 = [1,0,1,0,0,1,0,1];options =bvpset(‘stats’,’on’,’RelTol’,1e-5);
%solinit = bvpinit(m,y0);
% sol= bvp4c(@projfun,@projbc,solinit,options);
Z = zeros(numGr, length(m));
for i = 1:numGr
Gr= rr(i);
solinit = bvpinit(m, y0);
sol = bvp4c(@projfun, @projbc, solinit, options);
Z(i, 🙂 = deval(sol,m,1); % Store the z-axis data
end
[X, Y] = meshgrid(m, rr);
figure;
surf(X, Y, Z);
xlabel(‘x’);
ylabel(‘Prf’);
zlabel(‘Solution y(6,:)’);
title(‘Surface Plot of Solution’);
grid on;
function dy= projfun(~,y)
dy= zeros(8,1);
% alignComments
E = y(1);
dE = y(2);
F = y(3);
dF= y(4);
w = y(5);
dw=y(6);
t = y(7);
dt = y(8);
dy(1) = dE;
dy(2) = (((rhot/mut)*(a*(muf/rhof)^0.5*(E*F+E^2)+a*(muf/rhof)*w*dE-(mut/muf)*(rhof/rhot)*p*(1-0.01)*E+Gr*a*(muf/rhof)*sin(gamma)*(vb/(rhof*bef))*t)));
dy(3) = dF;
dy(4) = (((rhot/mut)*(b*(muf/rhof)^0.5*(F^2+F*E)+(muf/rhof)*b^0.5*a^(1.5)*dF)));
dy(5) =-(a*F+b*E);
dy(6) = (((rhot/mut)*((muf/rhof)^0.5*w*dw+Gr*b*(muf/rhof)*cos(gamma)*(vb/(rhof*bef))*t)));
dy(7) = dt;
dy(8)=prf*(1/(kt/kf))*(1/(1+((prf*Rd)/((kt/kf)))))*((vt/(rhof*cpf))*(muf/rhof)^0.5*w*dt-(mut/muf)*Ec*1*dw^2) ;
end
end
function res= projbc(ya,yb)
res= [ya(1)+1;
ya(3)-1;
ya(5);
ya(6);
ya(7)-1-(1/0.9)*ya(8);
yb(1)-0.01;
yb(3);
yb(7);
% yb(7);
];
end function sol= proj
clc;clf;clear;
%Relation of base fluid
rhof=997.1*10^-3;kf=0.613*10^5;cpf=4179*10^4;muf=10^-3*10;
alfaf=kf/(rhof*cpf);
bef=21*10^-5;
ky=muf/rhof;
disp(‘ky’);disp((muf/rhof));
%sigf=0.05*10^-8;
%Ag
ph1=0.01;
rho1=10500*10^-3;
cp1=235*10^4;
k1=429*10^5;be1=21*10^-5;
%sig1=0.74*10^-2;
%copper
ph2=0.01;
rho2=8933*10^-3;
cp2=385*10^4;
k2=400*10^5;
%sig2=5.96*10^-1;
be2=1.67*10^-5;
%Alumina
ph3=0.01;
rho3=3970*10^-3;
cp3=765*10^4;
k3=40*10^5;
be3=0.85*10^-5;
%sig3=3.5*10^-1;
%Relation of ternary hyprid
kn=kf*((k3+2*kf-2*ph3*(kf-k3))/(k3+2*kf+ph3*(kf-k3)));
kh=kn*((k2+2*kn-2*ph2*(kn-k2))/(k2+2*kn+ph2*(kn-k2)));
kt=kh*((k1+2*kh-2*ph1*(kh-k1))/(k1+2*kh+ph1*(kh-k1)));
mut= muf/((1-ph1)^2.5*(1-ph2)^2.5*(1-ph3)^2.5);
rhot=(1-ph1)*((1-ph2)*((1-ph3)+ph3*(rho3/rhof))+ph2*(rho2/rhof))+ph1*(rho1/rhof);
%vt=rhot*cpt
vt =(1-ph1)*((1-ph2)*((1-ph3)+ph3*((rho3*cp3)/(rhof*cpf)))+ph2*((rho2*cp2)/(rhof*cpf)))+ph1*((rho1*cp1)/(rhof*cpf));
%disp(‘vt’);disp(vt);
%vb=rho*betb
vb =(1-ph1)*((1-ph2)*((1-ph3)+ph3*((rho3*be3)/(rhof*bef)))+ph2*((rho2*be2)/(rhof*bef)))+ph1*((rho1*be1)/(rhof*bef));
%disp(‘vb’);disp(vb);disp(ky);
myLegend1 = {};myLegend2 = {};
%for i =1:numel(rr)
rr = [0 1 2];
numGr = numel(rr);
m = linspace(0,1);
a=-0.001;b=0.0001;p=-0.15/((1-0.01)*(mut/muf)*(rhof/rhot));
Ec=0.5;
gamma=pi/4;
prf=6.9;Rd=0.5;
Tw=273+50;Ti=273+27;deltaT=Tw-Ti;
disp(‘coe’);disp((mut/muf)*(rhof/rhot));
Lf=rhof*kf;
y0 = [1,0,1,0,0,1,0,1];options =bvpset(‘stats’,’on’,’RelTol’,1e-5);
%solinit = bvpinit(m,y0);
% sol= bvp4c(@projfun,@projbc,solinit,options);
Z = zeros(numGr, length(m));
for i = 1:numGr
Gr= rr(i);
solinit = bvpinit(m, y0);
sol = bvp4c(@projfun, @projbc, solinit, options);
Z(i, 🙂 = deval(sol,m,1); % Store the z-axis data
end
[X, Y] = meshgrid(m, rr);
figure;
surf(X, Y, Z);
xlabel(‘x’);
ylabel(‘Prf’);
zlabel(‘Solution y(6,:)’);
title(‘Surface Plot of Solution’);
grid on;
function dy= projfun(~,y)
dy= zeros(8,1);
% alignComments
E = y(1);
dE = y(2);
F = y(3);
dF= y(4);
w = y(5);
dw=y(6);
t = y(7);
dt = y(8);
dy(1) = dE;
dy(2) = (((rhot/mut)*(a*(muf/rhof)^0.5*(E*F+E^2)+a*(muf/rhof)*w*dE-(mut/muf)*(rhof/rhot)*p*(1-0.01)*E+Gr*a*(muf/rhof)*sin(gamma)*(vb/(rhof*bef))*t)));
dy(3) = dF;
dy(4) = (((rhot/mut)*(b*(muf/rhof)^0.5*(F^2+F*E)+(muf/rhof)*b^0.5*a^(1.5)*dF)));
dy(5) =-(a*F+b*E);
dy(6) = (((rhot/mut)*((muf/rhof)^0.5*w*dw+Gr*b*(muf/rhof)*cos(gamma)*(vb/(rhof*bef))*t)));
dy(7) = dt;
dy(8)=prf*(1/(kt/kf))*(1/(1+((prf*Rd)/((kt/kf)))))*((vt/(rhof*cpf))*(muf/rhof)^0.5*w*dt-(mut/muf)*Ec*1*dw^2) ;
end
end
function res= projbc(ya,yb)
res= [ya(1)+1;
ya(3)-1;
ya(5);
ya(6);
ya(7)-1-(1/0.9)*ya(8);
yb(1)-0.01;
yb(3);
yb(7);
% yb(7);
];
end bvp4c, ordinary differential equation MATLAB Answers — New Questions
WANT A HELP IN DTM MATLAP CODE
THIS IS A FILE DESCRIBE THE EQUATION AND THE , the Lagrangian -derived equations of motionTHIS IS A FILE DESCRIBE THE EQUATION AND THE , the Lagrangian -derived equations of motion THIS IS A FILE DESCRIBE THE EQUATION AND THE , the Lagrangian -derived equations of motion matlab, mathematics, code MATLAB Answers — New Questions
Question about convert PPO agent to ONNX
Greetings,
I encountered the error shown in figure when I tried to execute the ONNX on ubuntu at the first time.
Then I found it was the problem caused by rlContinuousGaussianActor, so I removed the mp_out and sdev layers and it worked!
But I don’t understand why it worked due to as my knowledge after I removed those layers it will mess up the PPO structure.
So what should I do? Keep working without mp_out and sdev layers or trying to fix them?
however, I have no idea about how to fix them, so I am confused.
Thank your time for watching or answering me.
Best wish,
HUANGreetings,
I encountered the error shown in figure when I tried to execute the ONNX on ubuntu at the first time.
Then I found it was the problem caused by rlContinuousGaussianActor, so I removed the mp_out and sdev layers and it worked!
But I don’t understand why it worked due to as my knowledge after I removed those layers it will mess up the PPO structure.
So what should I do? Keep working without mp_out and sdev layers or trying to fix them?
however, I have no idea about how to fix them, so I am confused.
Thank your time for watching or answering me.
Best wish,
HUAN Greetings,
I encountered the error shown in figure when I tried to execute the ONNX on ubuntu at the first time.
Then I found it was the problem caused by rlContinuousGaussianActor, so I removed the mp_out and sdev layers and it worked!
But I don’t understand why it worked due to as my knowledge after I removed those layers it will mess up the PPO structure.
So what should I do? Keep working without mp_out and sdev layers or trying to fix them?
however, I have no idea about how to fix them, so I am confused.
Thank your time for watching or answering me.
Best wish,
HUAN ppo, onnx, rlcontinuousgaussianactor MATLAB Answers — New Questions
Error using integral2Calc>integral2t/tensor (line 231) Input function must return ‘double’ or ‘single’ values. Found ‘sym’.
I’d like to know where the mistake in this code, and the solution
h = 0.00172; rho = 1620;
L = 100*h; c=L*L/4;
M=10; N=10;
syms xi eta
shape_w=sym(zeros(M,N)); x_m=sym(zeros(M,1)); y_n=sym(zeros(N,1));
for m=1:M
for n=1:N
x_m(m)=(xi^m)*(1+xi);
y_n(n)=(eta^n)*(1-eta)*(1+eta)^2;
shape_w(m,n)=x_m(m)*y_n(n);
end
end
fun=(shape_w*shape_w’);
M_w =c*(rho*h)*integral2(@(xi,eta)fun,-1,1,-1,1);I’d like to know where the mistake in this code, and the solution
h = 0.00172; rho = 1620;
L = 100*h; c=L*L/4;
M=10; N=10;
syms xi eta
shape_w=sym(zeros(M,N)); x_m=sym(zeros(M,1)); y_n=sym(zeros(N,1));
for m=1:M
for n=1:N
x_m(m)=(xi^m)*(1+xi);
y_n(n)=(eta^n)*(1-eta)*(1+eta)^2;
shape_w(m,n)=x_m(m)*y_n(n);
end
end
fun=(shape_w*shape_w’);
M_w =c*(rho*h)*integral2(@(xi,eta)fun,-1,1,-1,1); I’d like to know where the mistake in this code, and the solution
h = 0.00172; rho = 1620;
L = 100*h; c=L*L/4;
M=10; N=10;
syms xi eta
shape_w=sym(zeros(M,N)); x_m=sym(zeros(M,1)); y_n=sym(zeros(N,1));
for m=1:M
for n=1:N
x_m(m)=(xi^m)*(1+xi);
y_n(n)=(eta^n)*(1-eta)*(1+eta)^2;
shape_w(m,n)=x_m(m)*y_n(n);
end
end
fun=(shape_w*shape_w’);
M_w =c*(rho*h)*integral2(@(xi,eta)fun,-1,1,-1,1); how i can fix error using integral2calc integral2t/tensor (line 231)? MATLAB Answers — New Questions
What are the data confidentiality settings for MATLAB Copilot?
As some of the code being developed in MATLAB could be confidential, I am wondering if there are some Terms and Conditions or configuration parameters that must be set so that the MATLAB Copilot does not:
Get trained from the code
Uploads this protected information online
Expose to MathWorks or third parties the protected content
Could you explain how does it work regarding data confidentiality and how to set it up to prevent sharing or training from this confidential information?As some of the code being developed in MATLAB could be confidential, I am wondering if there are some Terms and Conditions or configuration parameters that must be set so that the MATLAB Copilot does not:
Get trained from the code
Uploads this protected information online
Expose to MathWorks or third parties the protected content
Could you explain how does it work regarding data confidentiality and how to set it up to prevent sharing or training from this confidential information? As some of the code being developed in MATLAB could be confidential, I am wondering if there are some Terms and Conditions or configuration parameters that must be set so that the MATLAB Copilot does not:
Get trained from the code
Uploads this protected information online
Expose to MathWorks or third parties the protected content
Could you explain how does it work regarding data confidentiality and how to set it up to prevent sharing or training from this confidential information? matlab, copilot, matlab-copilot MATLAB Answers — New Questions
Undefined function handle error when loading a neural network that contain a function layer
Hi everyone,
I created a neural network that uses a functionLayer that I defined by :
functionLayer(@Feature_wise_LM,Name="FiLM_64",Formattable=1,NumInputs=2,NumOutputs=1)
However, when I save the trained neural network with :
save("./trained_networks/FiLM", "trained_network");
and reload it in the same script with :
trained_network = load("./trained_networks/FiLM.mat");
trained_network = trained_network.trained_network;
I get the error :
Warning: While loading an object of class ‘dlnetwork’:
Error using nnet.internal.cnn.layer.GraphExecutor/propagate (line 354)
Execution failed during layer(s) ‘FiLM_64’.
Error in deep.internal.network.ExecutableNetwork/configureForInputsAndForwardOnLayer (line 347)
propagate(this, fcn, Xs, outputLayerIdx, outputLayerPortIdx);
Error in deep.internal.network.EditableNetwork/convertToDlnetwork (line 101)
[executableNetwork, layerOutputSizes] = configureForInputsAndForwardOnLayer(…
Error in dlnetwork.loadobj (line 741)
net = convertToDlnetwork(privateNet, exampleInputs, initializeNetworkWeights);
Caused by:
Undefined function handle.
Error in nnet.cnn.layer.FunctionLayer/predict (line 61)
[varargout{1:layer.NumOutputs}] = layer.PredictFcn(varargin{:});
I tried to save the function in a dedicated file "Feature_wise_LM.m" , but it didn’t workHi everyone,
I created a neural network that uses a functionLayer that I defined by :
functionLayer(@Feature_wise_LM,Name="FiLM_64",Formattable=1,NumInputs=2,NumOutputs=1)
However, when I save the trained neural network with :
save("./trained_networks/FiLM", "trained_network");
and reload it in the same script with :
trained_network = load("./trained_networks/FiLM.mat");
trained_network = trained_network.trained_network;
I get the error :
Warning: While loading an object of class ‘dlnetwork’:
Error using nnet.internal.cnn.layer.GraphExecutor/propagate (line 354)
Execution failed during layer(s) ‘FiLM_64’.
Error in deep.internal.network.ExecutableNetwork/configureForInputsAndForwardOnLayer (line 347)
propagate(this, fcn, Xs, outputLayerIdx, outputLayerPortIdx);
Error in deep.internal.network.EditableNetwork/convertToDlnetwork (line 101)
[executableNetwork, layerOutputSizes] = configureForInputsAndForwardOnLayer(…
Error in dlnetwork.loadobj (line 741)
net = convertToDlnetwork(privateNet, exampleInputs, initializeNetworkWeights);
Caused by:
Undefined function handle.
Error in nnet.cnn.layer.FunctionLayer/predict (line 61)
[varargout{1:layer.NumOutputs}] = layer.PredictFcn(varargin{:});
I tried to save the function in a dedicated file "Feature_wise_LM.m" , but it didn’t work Hi everyone,
I created a neural network that uses a functionLayer that I defined by :
functionLayer(@Feature_wise_LM,Name="FiLM_64",Formattable=1,NumInputs=2,NumOutputs=1)
However, when I save the trained neural network with :
save("./trained_networks/FiLM", "trained_network");
and reload it in the same script with :
trained_network = load("./trained_networks/FiLM.mat");
trained_network = trained_network.trained_network;
I get the error :
Warning: While loading an object of class ‘dlnetwork’:
Error using nnet.internal.cnn.layer.GraphExecutor/propagate (line 354)
Execution failed during layer(s) ‘FiLM_64’.
Error in deep.internal.network.ExecutableNetwork/configureForInputsAndForwardOnLayer (line 347)
propagate(this, fcn, Xs, outputLayerIdx, outputLayerPortIdx);
Error in deep.internal.network.EditableNetwork/convertToDlnetwork (line 101)
[executableNetwork, layerOutputSizes] = configureForInputsAndForwardOnLayer(…
Error in dlnetwork.loadobj (line 741)
net = convertToDlnetwork(privateNet, exampleInputs, initializeNetworkWeights);
Caused by:
Undefined function handle.
Error in nnet.cnn.layer.FunctionLayer/predict (line 61)
[varargout{1:layer.NumOutputs}] = layer.PredictFcn(varargin{:});
I tried to save the function in a dedicated file "Feature_wise_LM.m" , but it didn’t work deep learning, neural networks, function, matlab function MATLAB Answers — New Questions
How to process in real-time data from a SoC Device using SoC Blockset?
Dear all,
I am using SoC Blockset for a simple receiver design on AMD Zynq Ultrascale+ ZCU111 evaluation board.
Now, when my design is ready, built and deployed, I have an external mode model open and wondering how I can send the data from the ZCU111 board processor to the host computer and operate it in real-time.
I have already tried using Rate Transition block, UDP write block and IO data sink block in the external mode model to save the data to the host, what I received were the files, photos of which are attached
These are binary files, content of which can be loaded to workspace using fopen() and fread() functions. This is working, but would be better if I could receive the data and work with it on the development PC in real-time (e.g. using a different model or some script). Is there a way? Am I using the correct logic for the external mode model (to send the data to the development pc using UDP)?
Thank you!Dear all,
I am using SoC Blockset for a simple receiver design on AMD Zynq Ultrascale+ ZCU111 evaluation board.
Now, when my design is ready, built and deployed, I have an external mode model open and wondering how I can send the data from the ZCU111 board processor to the host computer and operate it in real-time.
I have already tried using Rate Transition block, UDP write block and IO data sink block in the external mode model to save the data to the host, what I received were the files, photos of which are attached
These are binary files, content of which can be loaded to workspace using fopen() and fread() functions. This is working, but would be better if I could receive the data and work with it on the development PC in real-time (e.g. using a different model or some script). Is there a way? Am I using the correct logic for the external mode model (to send the data to the development pc using UDP)?
Thank you! Dear all,
I am using SoC Blockset for a simple receiver design on AMD Zynq Ultrascale+ ZCU111 evaluation board.
Now, when my design is ready, built and deployed, I have an external mode model open and wondering how I can send the data from the ZCU111 board processor to the host computer and operate it in real-time.
I have already tried using Rate Transition block, UDP write block and IO data sink block in the external mode model to save the data to the host, what I received were the files, photos of which are attached
These are binary files, content of which can be loaded to workspace using fopen() and fread() functions. This is working, but would be better if I could receive the data and work with it on the development PC in real-time (e.g. using a different model or some script). Is there a way? Am I using the correct logic for the external mode model (to send the data to the development pc using UDP)?
Thank you! udp, soc blockset, fpga, zcu111, external mode, .csv MATLAB Answers — New Questions
How to simulate a rotor inter-turn fault in synchronous generator,using matlab programme.
I need programme format for simulating rotor inter-turn fault in synchronous generator.I need programme format for simulating rotor inter-turn fault in synchronous generator. I need programme format for simulating rotor inter-turn fault in synchronous generator. rotor inter-turn fault simulation. MATLAB Answers — New Questions
Accessing simParameters.Carrier inside MATLAB function block in Simulink
I am trying to implement PDSCH transceiver in simulink using simulink blocks and matlab functions.
I have already implemented this in Matlab code now want to implement in simulink, so now while doing this i am facing some problems using simParameters.Carrier in simulink matlab fucntion.
I have used variable carrier = simParameters.Carrier in matlab code. Now i want to access this as when i want to do OFDM Modulation i am using matlab function and while in this function i am writing
function txWaveform = OFDMModulator(pdschGrid, carrier)
txWaveform = nrOFDMModulate(carrier, pdschGrid);
end
But now i dont know how to access this carrier (in which complete configuration is present) in Matlab function.
Any suggestions on how I can get the data stored in this struct variable accessible inside the Simulink MATLAB function block? Thank you.I am trying to implement PDSCH transceiver in simulink using simulink blocks and matlab functions.
I have already implemented this in Matlab code now want to implement in simulink, so now while doing this i am facing some problems using simParameters.Carrier in simulink matlab fucntion.
I have used variable carrier = simParameters.Carrier in matlab code. Now i want to access this as when i want to do OFDM Modulation i am using matlab function and while in this function i am writing
function txWaveform = OFDMModulator(pdschGrid, carrier)
txWaveform = nrOFDMModulate(carrier, pdschGrid);
end
But now i dont know how to access this carrier (in which complete configuration is present) in Matlab function.
Any suggestions on how I can get the data stored in this struct variable accessible inside the Simulink MATLAB function block? Thank you. I am trying to implement PDSCH transceiver in simulink using simulink blocks and matlab functions.
I have already implemented this in Matlab code now want to implement in simulink, so now while doing this i am facing some problems using simParameters.Carrier in simulink matlab fucntion.
I have used variable carrier = simParameters.Carrier in matlab code. Now i want to access this as when i want to do OFDM Modulation i am using matlab function and while in this function i am writing
function txWaveform = OFDMModulator(pdschGrid, carrier)
txWaveform = nrOFDMModulate(carrier, pdschGrid);
end
But now i dont know how to access this carrier (in which complete configuration is present) in Matlab function.
Any suggestions on how I can get the data stored in this struct variable accessible inside the Simulink MATLAB function block? Thank you. #ofdm, #simulink, #modelworkspace, #workspace, #ofdmmodulation, data import MATLAB Answers — New Questions
Plot browser in R2025a?
in R2025a I can not find anymore the "plot browser" menu. I used a lot the hide/show options for lines.
Has this function disappeared?
Property Inspector is not really helpfull if many lines are present in the plot.in R2025a I can not find anymore the "plot browser" menu. I used a lot the hide/show options for lines.
Has this function disappeared?
Property Inspector is not really helpfull if many lines are present in the plot. in R2025a I can not find anymore the "plot browser" menu. I used a lot the hide/show options for lines.
Has this function disappeared?
Property Inspector is not really helpfull if many lines are present in the plot. plotedit MATLAB Answers — New Questions
install_unix_legacy not found during installation on MacOS
I’m trying to package Matlab R2025A MacOS intel processor version for silent install, I ran the downloader and got the file from download without installing option, however when I ran the install script within the downloaded file I got the following error
/bin/maca64/install_unix_legacy: cannot execute: No such file or directory
When I checked the downloaded files, that install_unix_legacy is indeed missing, is there anything special process to install this version?I’m trying to package Matlab R2025A MacOS intel processor version for silent install, I ran the downloader and got the file from download without installing option, however when I ran the install script within the downloaded file I got the following error
/bin/maca64/install_unix_legacy: cannot execute: No such file or directory
When I checked the downloaded files, that install_unix_legacy is indeed missing, is there anything special process to install this version? I’m trying to package Matlab R2025A MacOS intel processor version for silent install, I ran the downloader and got the file from download without installing option, however when I ran the install script within the downloaded file I got the following error
/bin/maca64/install_unix_legacy: cannot execute: No such file or directory
When I checked the downloaded files, that install_unix_legacy is indeed missing, is there anything special process to install this version? installation, mac, matlab MATLAB Answers — New Questions
Why do my Simulink PV module simulation characteristics appear this way?
I have tried to simulate a PV module with Simulink for a change in radiation and I am unable to get the characteristics.The P-V and I-V characteristics I am expecting are <http://ecee.colorado.edu/~ecen2060/materials/simulink/PV/PV_module_model.pdf here> . I used the repeating sequence for my voltage source and the repeating sequence stair for my insolation. I get incomplete characteristics such as the figures below.
<</matlabcentral/answers/uploaded_files/192/P-V%20and%20I-V%20characteristicspage-0.jpg>>
_ . What could be the problem? I have changed the time values and output values for the repeating sequence source and the simulation time but without success. Anyone with an explanation?I have tried to simulate a PV module with Simulink for a change in radiation and I am unable to get the characteristics.The P-V and I-V characteristics I am expecting are <http://ecee.colorado.edu/~ecen2060/materials/simulink/PV/PV_module_model.pdf here> . I used the repeating sequence for my voltage source and the repeating sequence stair for my insolation. I get incomplete characteristics such as the figures below.
<</matlabcentral/answers/uploaded_files/192/P-V%20and%20I-V%20characteristicspage-0.jpg>>
_ . What could be the problem? I have changed the time values and output values for the repeating sequence source and the simulation time but without success. Anyone with an explanation? I have tried to simulate a PV module with Simulink for a change in radiation and I am unable to get the characteristics.The P-V and I-V characteristics I am expecting are <http://ecee.colorado.edu/~ecen2060/materials/simulink/PV/PV_module_model.pdf here> . I used the repeating sequence for my voltage source and the repeating sequence stair for my insolation. I get incomplete characteristics such as the figures below.
<</matlabcentral/answers/uploaded_files/192/P-V%20and%20I-V%20characteristicspage-0.jpg>>
_ . What could be the problem? I have changed the time values and output values for the repeating sequence source and the simulation time but without success. Anyone with an explanation? pv module, simulink, simulation. MATLAB Answers — New Questions
looking for strictly recurrent and fast moving median implementation
I am looking for any suitable trick how to effectively compute moving window (length w) median. I know of course the movmedian function, but I need strictly recurrent native MATLAB function working sample by sample.
My naive solution, which is equivalent to the
output_median = movmedian(input_x,[w-1,0])
is as follows:
rng(‘default’)
% number of samples
N = 25;
% moving median windows length
w = 5;
% init history buffer and median
x_hist = rand;
med_new = x_hist;
% init input x vector
input_x = zeros(1,N);
input_x(1) = x_hist;
% init output median vector of length N
output_median = zeros(1,N);
output_median(1) = med_new;
for i = 2:N
x_new = rand;
[med_new,x_hist] = moving_median(x_hist,x_new,w);
input_x(i) = x_new;
output_median(i) = med_new;
end
where function moving_median is here:
function [med_new,x_hist] = moving_median(x_hist,x_new,w)
% Old length of history
wo = length(x_hist);
% Update history
x_hist = [x_hist(max(1,wo-w+2):wo),x_new]; % Grow history until size w, then append new x and remove oldest x
med_new = median(x_hist);
end
Any idea how to make this algorithm more effective (faster) a still strictly recurrent?
Target use case should works with window length:
w ~ 1e3 – 1e4 (!!!)
Additional notes:
fast moving median computing is always based on advanced data structures use like Heap or Queues, etc.
some sort-structure information could be stored in these structures and used at the next sample step to significant speed-up median computing
similar approach is used in movmedian function, but this function is not directly applicable on running-data streamI am looking for any suitable trick how to effectively compute moving window (length w) median. I know of course the movmedian function, but I need strictly recurrent native MATLAB function working sample by sample.
My naive solution, which is equivalent to the
output_median = movmedian(input_x,[w-1,0])
is as follows:
rng(‘default’)
% number of samples
N = 25;
% moving median windows length
w = 5;
% init history buffer and median
x_hist = rand;
med_new = x_hist;
% init input x vector
input_x = zeros(1,N);
input_x(1) = x_hist;
% init output median vector of length N
output_median = zeros(1,N);
output_median(1) = med_new;
for i = 2:N
x_new = rand;
[med_new,x_hist] = moving_median(x_hist,x_new,w);
input_x(i) = x_new;
output_median(i) = med_new;
end
where function moving_median is here:
function [med_new,x_hist] = moving_median(x_hist,x_new,w)
% Old length of history
wo = length(x_hist);
% Update history
x_hist = [x_hist(max(1,wo-w+2):wo),x_new]; % Grow history until size w, then append new x and remove oldest x
med_new = median(x_hist);
end
Any idea how to make this algorithm more effective (faster) a still strictly recurrent?
Target use case should works with window length:
w ~ 1e3 – 1e4 (!!!)
Additional notes:
fast moving median computing is always based on advanced data structures use like Heap or Queues, etc.
some sort-structure information could be stored in these structures and used at the next sample step to significant speed-up median computing
similar approach is used in movmedian function, but this function is not directly applicable on running-data stream I am looking for any suitable trick how to effectively compute moving window (length w) median. I know of course the movmedian function, but I need strictly recurrent native MATLAB function working sample by sample.
My naive solution, which is equivalent to the
output_median = movmedian(input_x,[w-1,0])
is as follows:
rng(‘default’)
% number of samples
N = 25;
% moving median windows length
w = 5;
% init history buffer and median
x_hist = rand;
med_new = x_hist;
% init input x vector
input_x = zeros(1,N);
input_x(1) = x_hist;
% init output median vector of length N
output_median = zeros(1,N);
output_median(1) = med_new;
for i = 2:N
x_new = rand;
[med_new,x_hist] = moving_median(x_hist,x_new,w);
input_x(i) = x_new;
output_median(i) = med_new;
end
where function moving_median is here:
function [med_new,x_hist] = moving_median(x_hist,x_new,w)
% Old length of history
wo = length(x_hist);
% Update history
x_hist = [x_hist(max(1,wo-w+2):wo),x_new]; % Grow history until size w, then append new x and remove oldest x
med_new = median(x_hist);
end
Any idea how to make this algorithm more effective (faster) a still strictly recurrent?
Target use case should works with window length:
w ~ 1e3 – 1e4 (!!!)
Additional notes:
fast moving median computing is always based on advanced data structures use like Heap or Queues, etc.
some sort-structure information could be stored in these structures and used at the next sample step to significant speed-up median computing
similar approach is used in movmedian function, but this function is not directly applicable on running-data stream moving, median MATLAB Answers — New Questions
Does SoC Builder do build optimizations, can I see the resources mapping and can I change it?
Dear all,
I am using SoC Blockset for a simple design for AMD Zynq Ultrascale+ ZCU111 evaluation board.
If I understand it correctly, the SoC Blockset add-on uses HDL coder to generate code for FPGA part of the SoC, but this is done through the SoC Builder interface, in which there are much less flexibility then in HDL coder. Does SoC Builder do some FPGA resource optimizations for build? How can I see the resource mapping? Can I change the mapping manually (for a better optimization, e.g.) or is it not possible to make a better mapping then the one produced automatically?
Thank you for your answers!Dear all,
I am using SoC Blockset for a simple design for AMD Zynq Ultrascale+ ZCU111 evaluation board.
If I understand it correctly, the SoC Blockset add-on uses HDL coder to generate code for FPGA part of the SoC, but this is done through the SoC Builder interface, in which there are much less flexibility then in HDL coder. Does SoC Builder do some FPGA resource optimizations for build? How can I see the resource mapping? Can I change the mapping manually (for a better optimization, e.g.) or is it not possible to make a better mapping then the one produced automatically?
Thank you for your answers! Dear all,
I am using SoC Blockset for a simple design for AMD Zynq Ultrascale+ ZCU111 evaluation board.
If I understand it correctly, the SoC Blockset add-on uses HDL coder to generate code for FPGA part of the SoC, but this is done through the SoC Builder interface, in which there are much less flexibility then in HDL coder. Does SoC Builder do some FPGA resource optimizations for build? How can I see the resource mapping? Can I change the mapping manually (for a better optimization, e.g.) or is it not possible to make a better mapping then the one produced automatically?
Thank you for your answers! hdl coder, soc builder, soc blockset, mapping, fpga, programmable logic, optimization MATLAB Answers — New Questions
Different output from ucover and musyn on different computers
Hello
I am working on control design using ucover and musyn functions with a colleague, and we are sharing scripts to generate controllers. We see that the same script does not produce the same controller on our computers, even though all inputs and Matlab versions are identical (24.2.0.2923080 (R2024b) Update 6).
Basically, we input FRD objects into ucover, which outputs an uncertainty model, which is processed and in turn fed into musyn, whcih outputs the controller.
I’ve found that the output from musyn is different, even if I fetch all inputs to musyn from my colleagues workspace. So the difference is introduced in the function itself, likely related to some optimization or floating point processing.
I’ve seen some other posts dealing with this, for example this one:
https://se.mathworks.com/matlabcentral/answers/130493-how-come-i-get-different-output-answers-with-the-same-matlab-version-the-same-code-installed-on-two?s_tid=ta_ans_results
We both get the same output from this prompt, so I assume differing BLAS versions is not a problem (both apparently use AVX2):
>> version(‘-blas’)
ans =
‘Intel(R) oneAPI Math Kernel Library Version 2024.1-Product Build 20240215 for Intel(R) 64 architecture applications (CNR branch AVX2)’
I’ve also found that, if we restrict MATALB to 1 CPU by running
maxNumCompThreads(1)
the output from the ucover function becomes identical (at least for our test case). But the output from musyn is still different on our computers, even with identical input. The difference is large enough to be very significant from a control design perspective, so this is a bit frustrating since we want to be able to reproduce the same controllers in the future, using the script as a recipe (for tracability).
Any tips are greatly appreciated, thanks!Hello
I am working on control design using ucover and musyn functions with a colleague, and we are sharing scripts to generate controllers. We see that the same script does not produce the same controller on our computers, even though all inputs and Matlab versions are identical (24.2.0.2923080 (R2024b) Update 6).
Basically, we input FRD objects into ucover, which outputs an uncertainty model, which is processed and in turn fed into musyn, whcih outputs the controller.
I’ve found that the output from musyn is different, even if I fetch all inputs to musyn from my colleagues workspace. So the difference is introduced in the function itself, likely related to some optimization or floating point processing.
I’ve seen some other posts dealing with this, for example this one:
https://se.mathworks.com/matlabcentral/answers/130493-how-come-i-get-different-output-answers-with-the-same-matlab-version-the-same-code-installed-on-two?s_tid=ta_ans_results
We both get the same output from this prompt, so I assume differing BLAS versions is not a problem (both apparently use AVX2):
>> version(‘-blas’)
ans =
‘Intel(R) oneAPI Math Kernel Library Version 2024.1-Product Build 20240215 for Intel(R) 64 architecture applications (CNR branch AVX2)’
I’ve also found that, if we restrict MATALB to 1 CPU by running
maxNumCompThreads(1)
the output from the ucover function becomes identical (at least for our test case). But the output from musyn is still different on our computers, even with identical input. The difference is large enough to be very significant from a control design perspective, so this is a bit frustrating since we want to be able to reproduce the same controllers in the future, using the script as a recipe (for tracability).
Any tips are greatly appreciated, thanks! Hello
I am working on control design using ucover and musyn functions with a colleague, and we are sharing scripts to generate controllers. We see that the same script does not produce the same controller on our computers, even though all inputs and Matlab versions are identical (24.2.0.2923080 (R2024b) Update 6).
Basically, we input FRD objects into ucover, which outputs an uncertainty model, which is processed and in turn fed into musyn, whcih outputs the controller.
I’ve found that the output from musyn is different, even if I fetch all inputs to musyn from my colleagues workspace. So the difference is introduced in the function itself, likely related to some optimization or floating point processing.
I’ve seen some other posts dealing with this, for example this one:
https://se.mathworks.com/matlabcentral/answers/130493-how-come-i-get-different-output-answers-with-the-same-matlab-version-the-same-code-installed-on-two?s_tid=ta_ans_results
We both get the same output from this prompt, so I assume differing BLAS versions is not a problem (both apparently use AVX2):
>> version(‘-blas’)
ans =
‘Intel(R) oneAPI Math Kernel Library Version 2024.1-Product Build 20240215 for Intel(R) 64 architecture applications (CNR branch AVX2)’
I’ve also found that, if we restrict MATALB to 1 CPU by running
maxNumCompThreads(1)
the output from the ucover function becomes identical (at least for our test case). But the output from musyn is still different on our computers, even with identical input. The difference is large enough to be very significant from a control design perspective, so this is a bit frustrating since we want to be able to reproduce the same controllers in the future, using the script as a recipe (for tracability).
Any tips are greatly appreciated, thanks! ucover, musyn, avx2 MATLAB Answers — New Questions
MATLAB Classification Learner App
"When choosing a Holdout validation method before training any of the available models so that you can compare all the models in your session using the same validation technique", does the Classification Learner train all models on the same training data samples and compute validation accuracy on the same validation data samples, or do the data samples differ each time a new model is trained?"When choosing a Holdout validation method before training any of the available models so that you can compare all the models in your session using the same validation technique", does the Classification Learner train all models on the same training data samples and compute validation accuracy on the same validation data samples, or do the data samples differ each time a new model is trained? "When choosing a Holdout validation method before training any of the available models so that you can compare all the models in your session using the same validation technique", does the Classification Learner train all models on the same training data samples and compute validation accuracy on the same validation data samples, or do the data samples differ each time a new model is trained? classifcation learner MATLAB Answers — New Questions
Help with HSDM model for lithium adsorption: simulated curves do not match experimental data (based on Jiang et al., 2020)
Hello everyone,
I’m trying to replicate the results from the paper by Jiang et al. (2020):
*“Application of concentration-dependent HSDM to the lithium adsorption from brine in fixed bed columns” – Separation and Purification Technology 241, 116682.
The paper models lithium adsorption in a fixed bed packed with Li–Al layered double hydroxide resins. It uses a concentration-dependent Homogeneous Surface Diffusion Model (HSDM), accounting for axial dispersion, film diffusion, surface diffusion, and Langmuir equilibrium. I’ve implemented a full MATLAB simulation including radial discretization inside the particles and a coupling with the axial profile.
I’ve followed the theoretical development very closely and used the same parameters as those reported by the authors. However, the breakthrough curves generated by my model still don’t fully match the experimental data shown in the paper (especially at intermediate values of C_out/C_in).
I suspect there may be a mistake in my implementation of either:
the mass balance in the fluid phase,
the boundary condition at the surface of the particle,
or how I define the rate of mass transfer using Kf.
I’m sharing my complete code below, and I would appreciate any suggestions or corrections you may have.
function hsdm_column_simulation_v2
% Full HSDM model with radial diffusion dependent on loading (Jiang et al. 2023)
clc; clear; close all
%% ==== PARÁMETROS DEL SISTEMA ==== –> %% ==== SYSTEM PARAMETERS ====
% Parámetros de la columna –> % Column parameters
Q = (15e-6)/60; % Brine flow rate [m3/s]
D = 0.02; % Column diameter [m]
A = pi/4 * D^2; % Cross-sectional area [m2]
v = Q/A; % Superficial or interstitial velocity [m/s]
epsilon = 0.355; % Bed void fraction
mu = 6.493e-3; % Fluid dynamic viscosity [Pa·s]
% Parámetros de la resina –> % Resin properties
rho = 1.3787; % Solid density [g/L] (coherent with q in mg/L)
dp = 0.65/1000; % Particle diameter [m]
Dm = 1.166e-5 / 10000; % Lithium diffusivity [m2/s]
R = 0.000325; % Particle radius [m]
Dax = 0.44*Dm + 0.83*v*dp; % Axial dispersion [m²/s] = 4.2983e-5
%% Isoterma de Langmuir –> %% Langmuir Isotherm
qmax = 5.9522; % Langmuir parameter [mg/g]
b = 0.03439; % Langmuir parameter [L/mg]
%% Difusión superficial dependiente de la carga –> %% Surface diffusion dependent on loading
Ds0 = 4e-14 ; % Surface diffusion coef. at 0 coverage [m²/s] (original was 3.2258e-14)
k_exp = 0.505; % Dimensionless constant
%% Correlaciones empíricas –> %% Empirical correlations
Re = (rho * v * dp) / mu;
Sc = mu / (rho * Dm);
Sh = 1.09 + 0.5 * Re^0.5 * Sc^(1/3);
Kf = Sh * Dm / dp; % 6.5386e-5
%% Discretización –> %% Discretization
L = 0.60; % Column height [m]
Nz = 20; % Axial nodes
Nr = 5; % Radial nodes per particle
dz = L / (Nz – 1);
dr = R / Nr;
%% Condiciones operacionales –> %% Operating conditions
cFeedVec = [300, 350, 400]; % mg/L
tf = 36000; % Final time [s] (600 min)
tspan = [0 tf];
colores = [‘b’,’g’,’r’];
%% Figura –> %% Plot
figure; hold on
for j = 1:length(cFeedVec)
cFeed = cFeedVec(j);
% Condiciones iniciales para el lecho y la partícula
c0 = zeros(Nz,1); % Initial concentration in fluid: C = 0
q0 = zeros(Nz*Nr,1); % Initial loading in particles: q = 0
y0 = [c0; q0];
% Agrupación de parámetros –> % Parameter grouping
param = struct(‘Nz’,Nz,’Nr’,Nr,’dz’,dz,’dr’,dr,’R’,R,…
‘epsilon’,epsilon,’rho’,rho,’v’,v,’Dax’,Dax,…
‘qmax’,qmax,’b’,b,’Ds0′,Ds0,’k’,k_exp,…
‘cFeed’,cFeed,’Kf’,Kf);
%% Resolución del sistema con ode15s –> %% System solution using ode15s
[T, Y] = ode15s(@(t,y) hsdm_rhs(t,y,param), tspan, y0);
% Ploteo de gráfico con salida normalizada –> % Plot normalized outlet
C_out = Y(:,Nz);
plot(T/60, C_out / cFeed, colores(j), ‘LineWidth’, 2, …
‘DisplayName’, [‘C_{in} = ‘ num2str(cFeed) ‘ mg/L’]);
end
% %% Evaluación de carga adsorbida para corroborar modelo
% Nz = param.Nz;
% Nr = param.Nr;
% R = param.R;
% dr = param.dr;
% qmax = param.qmax;
% q_final = reshape(Y(end, Nz+1:end), Nr, Nz); % q(r,z) at final time
% q_avg = trapz(linspace(0, R, Nr), q_final .* linspace(0, R, Nr)’, 1) * 2 / R^2;
% fprintf(‘n—– Saturation Analysis for C_in = %d mg/L —–n’, cFeed);
% fprintf(‘Global average q : %.4f mg/gn’, mean(q_avg));
% fprintf(‘Max q in column : %.4f mg/gn’, max(q_avg));
% fprintf(‘Theoretical qmax : %.4f mg/gn’, qmax);
%% Gráfico de Cout/Cin vs tiempo –> %% Plot Cout/Cin vs time
xlabel(‘Tiempo (min)’)
ylabel(‘C_{out} / C_{in}’)
title(‘Curva de ruptura Modelo HSDM’)
legend(‘Location’,’southeast’)
set(gca, ‘FontName’, ‘Palatino Linotype’) % Axes font
box on
%% Puntos experimentales aproximados (visualmente desde el paper)
t_exp = 0:30:600;
Cexp_300 = [0.00 0.22 0.36 0.48 0.57 0.63 0.69 0.73 0.77 0.80 …
0.82 0.84 0.85 0.86 0.87 0.88 0.88 0.89 0.89 0.89 0.90];
Cexp_350 = [0.00 0.26 0.40 0.53 0.62 0.69 0.74 0.78 0.81 0.83 …
0.85 0.86 0.87 0.88 0.88 0.89 0.89 0.90 0.90 0.90 0.91];
Cexp_400 = [0.00 0.29 0.45 0.59 0.68 0.75 0.79 0.83 0.85 0.87 …
0.88 0.89 0.90 0.90 0.91 0.91 0.91 0.91 0.92 0.92 0.92];
% Superponer puntos experimentales –> % Plot experimental data
plot(t_exp, Cexp_400, ‘r^’, ‘MarkerFaceColor’, ‘r’, ‘DisplayName’, ‘Exp 400 mg/L’)
plot(t_exp, Cexp_350, ‘go’, ‘MarkerFaceColor’, ‘g’, ‘DisplayName’, ‘Exp 350 mg/L’)
plot(t_exp, Cexp_300, ‘bs’, ‘MarkerFaceColor’, ‘b’, ‘DisplayName’, ‘Exp 300 mg/L’)
end
%% FUNCIÓN RHS DEL MODELO HSDM –> %% RHS FUNCTION FOR HSDM MODEL
function dydt = hsdm_rhs(~, y, p)
% Extraer parámetros –> % Extract parameters
Nz = p.Nz; Nr = p.Nr; dz = p.dz; dr = p.dr;
R = p.R; epsilon = p.epsilon; rho = p.rho;
v = p.v; Dax = p.Dax; qmax = p.qmax; b = p.b;
Ds0 = p.Ds0; k_exp = p.k; cFeed = p.cFeed; Kf = p.Kf;
% Separar variables –> % Split variables
c = y(1:Nz);
q = reshape(y(Nz+1:end), Nr, Nz); % q(r,z)
% Inicializar derivadas –> % Initialize derivatives
dc_dt = zeros(Nz,1);
dq_dt = zeros(Nr,Nz);
%% Balance de masa axial (fase fluida) –> %% Mass balance (fluid phase)
for i = 2:Nz-1
dcdz = (c(i+1)-c(i-1))/(2*dz);
d2cdz2 = (c(i+1) – 2*c(i) + c(i-1))/dz^2;
qsurf = q(end,i);
Csurf = c(i);
dqR_dt = (3/R) * Kf * (Csurf – qsurf);
dc_dt(i) = Dax * d2cdz2 – v * dcdz – ((1 – epsilon)/epsilon) * rho * 1000 * dqR_dt;
end
%% Condiciones de contorno en la columna
% Entrada z = 0 – tipo Danckwerts
qsurf = q(end,1);
Csurf = c(1);
dqR_dt_in = (3 / R) * Kf * (Csurf – qsurf);
dc_dt(1) = Dax * (c(2) – c(1)) / dz^2 – v * (cFeed – c(1)) – ((1 – epsilon)/epsilon) * rho * 1000 * dqR_dt_in;
% Salida z = L
dc_dt(end) = Dax * (c(end-1) – c(end)) / dz;
%% Difusión radial al interior de la partícula
for iz = 1:Nz
for ir = 2:Nr-1
rq = (ir-1)*dr;
d2q = (q(ir+1,iz) – 2*q(ir,iz) + q(ir-1,iz)) / dr^2;
Ds = Ds0 * (1 – q(ir,iz)/qmax)^k_exp;
dq_dt(ir,iz) = Ds * (d2q + (2/rq)*(q(ir+1,iz)-q(ir-1,iz))/(2*dr));
end
% Centro de la partícula
dq_dt(1,iz) = 0;
% Superficie de la partícula
q_eq = (qmax * b * c(iz)) / (1 + b * c(iz));
dq_dt(Nr,iz) = 3 * Kf / R * (q_eq – q(Nr,iz));
end
% Vector final
dydt = [dc_dt; dq_dt(:)];
endHello everyone,
I’m trying to replicate the results from the paper by Jiang et al. (2020):
*“Application of concentration-dependent HSDM to the lithium adsorption from brine in fixed bed columns” – Separation and Purification Technology 241, 116682.
The paper models lithium adsorption in a fixed bed packed with Li–Al layered double hydroxide resins. It uses a concentration-dependent Homogeneous Surface Diffusion Model (HSDM), accounting for axial dispersion, film diffusion, surface diffusion, and Langmuir equilibrium. I’ve implemented a full MATLAB simulation including radial discretization inside the particles and a coupling with the axial profile.
I’ve followed the theoretical development very closely and used the same parameters as those reported by the authors. However, the breakthrough curves generated by my model still don’t fully match the experimental data shown in the paper (especially at intermediate values of C_out/C_in).
I suspect there may be a mistake in my implementation of either:
the mass balance in the fluid phase,
the boundary condition at the surface of the particle,
or how I define the rate of mass transfer using Kf.
I’m sharing my complete code below, and I would appreciate any suggestions or corrections you may have.
function hsdm_column_simulation_v2
% Full HSDM model with radial diffusion dependent on loading (Jiang et al. 2023)
clc; clear; close all
%% ==== PARÁMETROS DEL SISTEMA ==== –> %% ==== SYSTEM PARAMETERS ====
% Parámetros de la columna –> % Column parameters
Q = (15e-6)/60; % Brine flow rate [m3/s]
D = 0.02; % Column diameter [m]
A = pi/4 * D^2; % Cross-sectional area [m2]
v = Q/A; % Superficial or interstitial velocity [m/s]
epsilon = 0.355; % Bed void fraction
mu = 6.493e-3; % Fluid dynamic viscosity [Pa·s]
% Parámetros de la resina –> % Resin properties
rho = 1.3787; % Solid density [g/L] (coherent with q in mg/L)
dp = 0.65/1000; % Particle diameter [m]
Dm = 1.166e-5 / 10000; % Lithium diffusivity [m2/s]
R = 0.000325; % Particle radius [m]
Dax = 0.44*Dm + 0.83*v*dp; % Axial dispersion [m²/s] = 4.2983e-5
%% Isoterma de Langmuir –> %% Langmuir Isotherm
qmax = 5.9522; % Langmuir parameter [mg/g]
b = 0.03439; % Langmuir parameter [L/mg]
%% Difusión superficial dependiente de la carga –> %% Surface diffusion dependent on loading
Ds0 = 4e-14 ; % Surface diffusion coef. at 0 coverage [m²/s] (original was 3.2258e-14)
k_exp = 0.505; % Dimensionless constant
%% Correlaciones empíricas –> %% Empirical correlations
Re = (rho * v * dp) / mu;
Sc = mu / (rho * Dm);
Sh = 1.09 + 0.5 * Re^0.5 * Sc^(1/3);
Kf = Sh * Dm / dp; % 6.5386e-5
%% Discretización –> %% Discretization
L = 0.60; % Column height [m]
Nz = 20; % Axial nodes
Nr = 5; % Radial nodes per particle
dz = L / (Nz – 1);
dr = R / Nr;
%% Condiciones operacionales –> %% Operating conditions
cFeedVec = [300, 350, 400]; % mg/L
tf = 36000; % Final time [s] (600 min)
tspan = [0 tf];
colores = [‘b’,’g’,’r’];
%% Figura –> %% Plot
figure; hold on
for j = 1:length(cFeedVec)
cFeed = cFeedVec(j);
% Condiciones iniciales para el lecho y la partícula
c0 = zeros(Nz,1); % Initial concentration in fluid: C = 0
q0 = zeros(Nz*Nr,1); % Initial loading in particles: q = 0
y0 = [c0; q0];
% Agrupación de parámetros –> % Parameter grouping
param = struct(‘Nz’,Nz,’Nr’,Nr,’dz’,dz,’dr’,dr,’R’,R,…
‘epsilon’,epsilon,’rho’,rho,’v’,v,’Dax’,Dax,…
‘qmax’,qmax,’b’,b,’Ds0′,Ds0,’k’,k_exp,…
‘cFeed’,cFeed,’Kf’,Kf);
%% Resolución del sistema con ode15s –> %% System solution using ode15s
[T, Y] = ode15s(@(t,y) hsdm_rhs(t,y,param), tspan, y0);
% Ploteo de gráfico con salida normalizada –> % Plot normalized outlet
C_out = Y(:,Nz);
plot(T/60, C_out / cFeed, colores(j), ‘LineWidth’, 2, …
‘DisplayName’, [‘C_{in} = ‘ num2str(cFeed) ‘ mg/L’]);
end
% %% Evaluación de carga adsorbida para corroborar modelo
% Nz = param.Nz;
% Nr = param.Nr;
% R = param.R;
% dr = param.dr;
% qmax = param.qmax;
% q_final = reshape(Y(end, Nz+1:end), Nr, Nz); % q(r,z) at final time
% q_avg = trapz(linspace(0, R, Nr), q_final .* linspace(0, R, Nr)’, 1) * 2 / R^2;
% fprintf(‘n—– Saturation Analysis for C_in = %d mg/L —–n’, cFeed);
% fprintf(‘Global average q : %.4f mg/gn’, mean(q_avg));
% fprintf(‘Max q in column : %.4f mg/gn’, max(q_avg));
% fprintf(‘Theoretical qmax : %.4f mg/gn’, qmax);
%% Gráfico de Cout/Cin vs tiempo –> %% Plot Cout/Cin vs time
xlabel(‘Tiempo (min)’)
ylabel(‘C_{out} / C_{in}’)
title(‘Curva de ruptura Modelo HSDM’)
legend(‘Location’,’southeast’)
set(gca, ‘FontName’, ‘Palatino Linotype’) % Axes font
box on
%% Puntos experimentales aproximados (visualmente desde el paper)
t_exp = 0:30:600;
Cexp_300 = [0.00 0.22 0.36 0.48 0.57 0.63 0.69 0.73 0.77 0.80 …
0.82 0.84 0.85 0.86 0.87 0.88 0.88 0.89 0.89 0.89 0.90];
Cexp_350 = [0.00 0.26 0.40 0.53 0.62 0.69 0.74 0.78 0.81 0.83 …
0.85 0.86 0.87 0.88 0.88 0.89 0.89 0.90 0.90 0.90 0.91];
Cexp_400 = [0.00 0.29 0.45 0.59 0.68 0.75 0.79 0.83 0.85 0.87 …
0.88 0.89 0.90 0.90 0.91 0.91 0.91 0.91 0.92 0.92 0.92];
% Superponer puntos experimentales –> % Plot experimental data
plot(t_exp, Cexp_400, ‘r^’, ‘MarkerFaceColor’, ‘r’, ‘DisplayName’, ‘Exp 400 mg/L’)
plot(t_exp, Cexp_350, ‘go’, ‘MarkerFaceColor’, ‘g’, ‘DisplayName’, ‘Exp 350 mg/L’)
plot(t_exp, Cexp_300, ‘bs’, ‘MarkerFaceColor’, ‘b’, ‘DisplayName’, ‘Exp 300 mg/L’)
end
%% FUNCIÓN RHS DEL MODELO HSDM –> %% RHS FUNCTION FOR HSDM MODEL
function dydt = hsdm_rhs(~, y, p)
% Extraer parámetros –> % Extract parameters
Nz = p.Nz; Nr = p.Nr; dz = p.dz; dr = p.dr;
R = p.R; epsilon = p.epsilon; rho = p.rho;
v = p.v; Dax = p.Dax; qmax = p.qmax; b = p.b;
Ds0 = p.Ds0; k_exp = p.k; cFeed = p.cFeed; Kf = p.Kf;
% Separar variables –> % Split variables
c = y(1:Nz);
q = reshape(y(Nz+1:end), Nr, Nz); % q(r,z)
% Inicializar derivadas –> % Initialize derivatives
dc_dt = zeros(Nz,1);
dq_dt = zeros(Nr,Nz);
%% Balance de masa axial (fase fluida) –> %% Mass balance (fluid phase)
for i = 2:Nz-1
dcdz = (c(i+1)-c(i-1))/(2*dz);
d2cdz2 = (c(i+1) – 2*c(i) + c(i-1))/dz^2;
qsurf = q(end,i);
Csurf = c(i);
dqR_dt = (3/R) * Kf * (Csurf – qsurf);
dc_dt(i) = Dax * d2cdz2 – v * dcdz – ((1 – epsilon)/epsilon) * rho * 1000 * dqR_dt;
end
%% Condiciones de contorno en la columna
% Entrada z = 0 – tipo Danckwerts
qsurf = q(end,1);
Csurf = c(1);
dqR_dt_in = (3 / R) * Kf * (Csurf – qsurf);
dc_dt(1) = Dax * (c(2) – c(1)) / dz^2 – v * (cFeed – c(1)) – ((1 – epsilon)/epsilon) * rho * 1000 * dqR_dt_in;
% Salida z = L
dc_dt(end) = Dax * (c(end-1) – c(end)) / dz;
%% Difusión radial al interior de la partícula
for iz = 1:Nz
for ir = 2:Nr-1
rq = (ir-1)*dr;
d2q = (q(ir+1,iz) – 2*q(ir,iz) + q(ir-1,iz)) / dr^2;
Ds = Ds0 * (1 – q(ir,iz)/qmax)^k_exp;
dq_dt(ir,iz) = Ds * (d2q + (2/rq)*(q(ir+1,iz)-q(ir-1,iz))/(2*dr));
end
% Centro de la partícula
dq_dt(1,iz) = 0;
% Superficie de la partícula
q_eq = (qmax * b * c(iz)) / (1 + b * c(iz));
dq_dt(Nr,iz) = 3 * Kf / R * (q_eq – q(Nr,iz));
end
% Vector final
dydt = [dc_dt; dq_dt(:)];
end Hello everyone,
I’m trying to replicate the results from the paper by Jiang et al. (2020):
*“Application of concentration-dependent HSDM to the lithium adsorption from brine in fixed bed columns” – Separation and Purification Technology 241, 116682.
The paper models lithium adsorption in a fixed bed packed with Li–Al layered double hydroxide resins. It uses a concentration-dependent Homogeneous Surface Diffusion Model (HSDM), accounting for axial dispersion, film diffusion, surface diffusion, and Langmuir equilibrium. I’ve implemented a full MATLAB simulation including radial discretization inside the particles and a coupling with the axial profile.
I’ve followed the theoretical development very closely and used the same parameters as those reported by the authors. However, the breakthrough curves generated by my model still don’t fully match the experimental data shown in the paper (especially at intermediate values of C_out/C_in).
I suspect there may be a mistake in my implementation of either:
the mass balance in the fluid phase,
the boundary condition at the surface of the particle,
or how I define the rate of mass transfer using Kf.
I’m sharing my complete code below, and I would appreciate any suggestions or corrections you may have.
function hsdm_column_simulation_v2
% Full HSDM model with radial diffusion dependent on loading (Jiang et al. 2023)
clc; clear; close all
%% ==== PARÁMETROS DEL SISTEMA ==== –> %% ==== SYSTEM PARAMETERS ====
% Parámetros de la columna –> % Column parameters
Q = (15e-6)/60; % Brine flow rate [m3/s]
D = 0.02; % Column diameter [m]
A = pi/4 * D^2; % Cross-sectional area [m2]
v = Q/A; % Superficial or interstitial velocity [m/s]
epsilon = 0.355; % Bed void fraction
mu = 6.493e-3; % Fluid dynamic viscosity [Pa·s]
% Parámetros de la resina –> % Resin properties
rho = 1.3787; % Solid density [g/L] (coherent with q in mg/L)
dp = 0.65/1000; % Particle diameter [m]
Dm = 1.166e-5 / 10000; % Lithium diffusivity [m2/s]
R = 0.000325; % Particle radius [m]
Dax = 0.44*Dm + 0.83*v*dp; % Axial dispersion [m²/s] = 4.2983e-5
%% Isoterma de Langmuir –> %% Langmuir Isotherm
qmax = 5.9522; % Langmuir parameter [mg/g]
b = 0.03439; % Langmuir parameter [L/mg]
%% Difusión superficial dependiente de la carga –> %% Surface diffusion dependent on loading
Ds0 = 4e-14 ; % Surface diffusion coef. at 0 coverage [m²/s] (original was 3.2258e-14)
k_exp = 0.505; % Dimensionless constant
%% Correlaciones empíricas –> %% Empirical correlations
Re = (rho * v * dp) / mu;
Sc = mu / (rho * Dm);
Sh = 1.09 + 0.5 * Re^0.5 * Sc^(1/3);
Kf = Sh * Dm / dp; % 6.5386e-5
%% Discretización –> %% Discretization
L = 0.60; % Column height [m]
Nz = 20; % Axial nodes
Nr = 5; % Radial nodes per particle
dz = L / (Nz – 1);
dr = R / Nr;
%% Condiciones operacionales –> %% Operating conditions
cFeedVec = [300, 350, 400]; % mg/L
tf = 36000; % Final time [s] (600 min)
tspan = [0 tf];
colores = [‘b’,’g’,’r’];
%% Figura –> %% Plot
figure; hold on
for j = 1:length(cFeedVec)
cFeed = cFeedVec(j);
% Condiciones iniciales para el lecho y la partícula
c0 = zeros(Nz,1); % Initial concentration in fluid: C = 0
q0 = zeros(Nz*Nr,1); % Initial loading in particles: q = 0
y0 = [c0; q0];
% Agrupación de parámetros –> % Parameter grouping
param = struct(‘Nz’,Nz,’Nr’,Nr,’dz’,dz,’dr’,dr,’R’,R,…
‘epsilon’,epsilon,’rho’,rho,’v’,v,’Dax’,Dax,…
‘qmax’,qmax,’b’,b,’Ds0′,Ds0,’k’,k_exp,…
‘cFeed’,cFeed,’Kf’,Kf);
%% Resolución del sistema con ode15s –> %% System solution using ode15s
[T, Y] = ode15s(@(t,y) hsdm_rhs(t,y,param), tspan, y0);
% Ploteo de gráfico con salida normalizada –> % Plot normalized outlet
C_out = Y(:,Nz);
plot(T/60, C_out / cFeed, colores(j), ‘LineWidth’, 2, …
‘DisplayName’, [‘C_{in} = ‘ num2str(cFeed) ‘ mg/L’]);
end
% %% Evaluación de carga adsorbida para corroborar modelo
% Nz = param.Nz;
% Nr = param.Nr;
% R = param.R;
% dr = param.dr;
% qmax = param.qmax;
% q_final = reshape(Y(end, Nz+1:end), Nr, Nz); % q(r,z) at final time
% q_avg = trapz(linspace(0, R, Nr), q_final .* linspace(0, R, Nr)’, 1) * 2 / R^2;
% fprintf(‘n—– Saturation Analysis for C_in = %d mg/L —–n’, cFeed);
% fprintf(‘Global average q : %.4f mg/gn’, mean(q_avg));
% fprintf(‘Max q in column : %.4f mg/gn’, max(q_avg));
% fprintf(‘Theoretical qmax : %.4f mg/gn’, qmax);
%% Gráfico de Cout/Cin vs tiempo –> %% Plot Cout/Cin vs time
xlabel(‘Tiempo (min)’)
ylabel(‘C_{out} / C_{in}’)
title(‘Curva de ruptura Modelo HSDM’)
legend(‘Location’,’southeast’)
set(gca, ‘FontName’, ‘Palatino Linotype’) % Axes font
box on
%% Puntos experimentales aproximados (visualmente desde el paper)
t_exp = 0:30:600;
Cexp_300 = [0.00 0.22 0.36 0.48 0.57 0.63 0.69 0.73 0.77 0.80 …
0.82 0.84 0.85 0.86 0.87 0.88 0.88 0.89 0.89 0.89 0.90];
Cexp_350 = [0.00 0.26 0.40 0.53 0.62 0.69 0.74 0.78 0.81 0.83 …
0.85 0.86 0.87 0.88 0.88 0.89 0.89 0.90 0.90 0.90 0.91];
Cexp_400 = [0.00 0.29 0.45 0.59 0.68 0.75 0.79 0.83 0.85 0.87 …
0.88 0.89 0.90 0.90 0.91 0.91 0.91 0.91 0.92 0.92 0.92];
% Superponer puntos experimentales –> % Plot experimental data
plot(t_exp, Cexp_400, ‘r^’, ‘MarkerFaceColor’, ‘r’, ‘DisplayName’, ‘Exp 400 mg/L’)
plot(t_exp, Cexp_350, ‘go’, ‘MarkerFaceColor’, ‘g’, ‘DisplayName’, ‘Exp 350 mg/L’)
plot(t_exp, Cexp_300, ‘bs’, ‘MarkerFaceColor’, ‘b’, ‘DisplayName’, ‘Exp 300 mg/L’)
end
%% FUNCIÓN RHS DEL MODELO HSDM –> %% RHS FUNCTION FOR HSDM MODEL
function dydt = hsdm_rhs(~, y, p)
% Extraer parámetros –> % Extract parameters
Nz = p.Nz; Nr = p.Nr; dz = p.dz; dr = p.dr;
R = p.R; epsilon = p.epsilon; rho = p.rho;
v = p.v; Dax = p.Dax; qmax = p.qmax; b = p.b;
Ds0 = p.Ds0; k_exp = p.k; cFeed = p.cFeed; Kf = p.Kf;
% Separar variables –> % Split variables
c = y(1:Nz);
q = reshape(y(Nz+1:end), Nr, Nz); % q(r,z)
% Inicializar derivadas –> % Initialize derivatives
dc_dt = zeros(Nz,1);
dq_dt = zeros(Nr,Nz);
%% Balance de masa axial (fase fluida) –> %% Mass balance (fluid phase)
for i = 2:Nz-1
dcdz = (c(i+1)-c(i-1))/(2*dz);
d2cdz2 = (c(i+1) – 2*c(i) + c(i-1))/dz^2;
qsurf = q(end,i);
Csurf = c(i);
dqR_dt = (3/R) * Kf * (Csurf – qsurf);
dc_dt(i) = Dax * d2cdz2 – v * dcdz – ((1 – epsilon)/epsilon) * rho * 1000 * dqR_dt;
end
%% Condiciones de contorno en la columna
% Entrada z = 0 – tipo Danckwerts
qsurf = q(end,1);
Csurf = c(1);
dqR_dt_in = (3 / R) * Kf * (Csurf – qsurf);
dc_dt(1) = Dax * (c(2) – c(1)) / dz^2 – v * (cFeed – c(1)) – ((1 – epsilon)/epsilon) * rho * 1000 * dqR_dt_in;
% Salida z = L
dc_dt(end) = Dax * (c(end-1) – c(end)) / dz;
%% Difusión radial al interior de la partícula
for iz = 1:Nz
for ir = 2:Nr-1
rq = (ir-1)*dr;
d2q = (q(ir+1,iz) – 2*q(ir,iz) + q(ir-1,iz)) / dr^2;
Ds = Ds0 * (1 – q(ir,iz)/qmax)^k_exp;
dq_dt(ir,iz) = Ds * (d2q + (2/rq)*(q(ir+1,iz)-q(ir-1,iz))/(2*dr));
end
% Centro de la partícula
dq_dt(1,iz) = 0;
% Superficie de la partícula
q_eq = (qmax * b * c(iz)) / (1 + b * c(iz));
dq_dt(Nr,iz) = 3 * Kf / R * (q_eq – q(Nr,iz));
end
% Vector final
dydt = [dc_dt; dq_dt(:)];
end adsorption, hsdm, resin, adsorption column, lithium MATLAB Answers — New Questions
Querying data from enum arrays using C API
I am passing a struct as a block dialog parameter to an S-function. The struct is deeply nested and contains some fields that are enumeration arrays. The enums are defined in matlab and inherit from Simulink.IntType. I am able to grab the data fine when the field is a scalar, as in just one element. However, if the field is an enumeration array, then I cannot. For example, I have an enumeration array that in matlab shows size = [16×1]. I have a corresponding C type array of size 16, and type of the enumeration, also defined in C. I’m confused as to how to copy the data from the enum array since I’m getting rows =1, cols = 1, and numElements = 1 when running the following code.
My code is as follows:
const char *class_name = mxGetClassName(matlabArray); -> This returns the expected enumeration type name.
mxArray *enumArrayField = mxGetField(parentField, 0, “myEnumInstanceName”);
size_t rows = mxGetM(enumArrayField); %-> This returns 1
size_t cols = mxGetN(enumArrayField); %-> This also returns 1
size_t numElements = mxGetNumberOfElements(matlabArray); %-> This also returns 1.
//
void *raw_data = mxGetData(matlabArray); %->i tried to grab the data this way but doesn’t seem to work because i cannot iterate on it
size_t element_size = mxGetElementSize(matlabArray); %-> This returns 8 bytesI am passing a struct as a block dialog parameter to an S-function. The struct is deeply nested and contains some fields that are enumeration arrays. The enums are defined in matlab and inherit from Simulink.IntType. I am able to grab the data fine when the field is a scalar, as in just one element. However, if the field is an enumeration array, then I cannot. For example, I have an enumeration array that in matlab shows size = [16×1]. I have a corresponding C type array of size 16, and type of the enumeration, also defined in C. I’m confused as to how to copy the data from the enum array since I’m getting rows =1, cols = 1, and numElements = 1 when running the following code.
My code is as follows:
const char *class_name = mxGetClassName(matlabArray); -> This returns the expected enumeration type name.
mxArray *enumArrayField = mxGetField(parentField, 0, “myEnumInstanceName”);
size_t rows = mxGetM(enumArrayField); %-> This returns 1
size_t cols = mxGetN(enumArrayField); %-> This also returns 1
size_t numElements = mxGetNumberOfElements(matlabArray); %-> This also returns 1.
//
void *raw_data = mxGetData(matlabArray); %->i tried to grab the data this way but doesn’t seem to work because i cannot iterate on it
size_t element_size = mxGetElementSize(matlabArray); %-> This returns 8 bytes I am passing a struct as a block dialog parameter to an S-function. The struct is deeply nested and contains some fields that are enumeration arrays. The enums are defined in matlab and inherit from Simulink.IntType. I am able to grab the data fine when the field is a scalar, as in just one element. However, if the field is an enumeration array, then I cannot. For example, I have an enumeration array that in matlab shows size = [16×1]. I have a corresponding C type array of size 16, and type of the enumeration, also defined in C. I’m confused as to how to copy the data from the enum array since I’m getting rows =1, cols = 1, and numElements = 1 when running the following code.
My code is as follows:
const char *class_name = mxGetClassName(matlabArray); -> This returns the expected enumeration type name.
mxArray *enumArrayField = mxGetField(parentField, 0, “myEnumInstanceName”);
size_t rows = mxGetM(enumArrayField); %-> This returns 1
size_t cols = mxGetN(enumArrayField); %-> This also returns 1
size_t numElements = mxGetNumberOfElements(matlabArray); %-> This also returns 1.
//
void *raw_data = mxGetData(matlabArray); %->i tried to grab the data this way but doesn’t seem to work because i cannot iterate on it
size_t element_size = mxGetElementSize(matlabArray); %-> This returns 8 bytes simulink, matlab, matlab coder MATLAB Answers — New Questions