Tag Archives: matlab
Solving the equations of Simscape’s Ejector with vsolve
Dear Everyone,
I have written a Matlab script based on the equations of the Ejector in Simscape (https://www.mathworks.com/help/hydro/ref/ejectorg.html). I am not good at using Simscape and I am having difficulties running the Ejector in Simscape.
My script calculates Pm (pressure after mixing ) using fsolve. I have modified the equations a bit as I think γ should be different for the two streams, therefore I have kp (γ of the primary stream) and ks (γ of the secondary stream). I also included an iteration to calculate the stagnation temperatures of the two streams since the documentation of the Ejector states that the block assumes that Tp and Ts (temperatures of primary and secondary streams) are equal to their primary flow stagnation temperature. These temperatures are needed for the calculation of Tm (temperature of mixing). The stagnation temperature depends on Mm (Mach number of mixing) which depends on Tm which in turn depends on the stagnation temperatures.
I am considering a case where the primary stream is CO2 at 1MPa and 20°C and the secondary stream is air at 0.1 MPa and 20°C, and I calculate Pm = 0.0012 MPa and Mm = 0.033. I think these results are wrong, could someone please confirm this? It seems that my solver calculates the same Pm regardless of Pp (primary pressure) and a Pm always close to Ps (secondary pressure).
I am attaching the m files needed to run the script below. "ejector_solver.m". "Ejector_equations_star" uses the same equations as in "Ejector_equations" but replaces Pm with Pm_star to calculate the critical diffuser outlet pressure.
Also, does anyone know how the cross-sectional areas of the three ports are used? They need to be specified for the Ejector in Simscape but I am not sure where they appear in the equations.
I am grateful for any help you can provide.
Best regards,
clearvars; close all; clc;
% Primary stream
Primary_fluid = ‘CO2’;
Pp = 1; % [MPa] Pressure of primary stream
Tp = 20 + 273.15; % [K] Temperature of primary stream
kp = 1.3589; % Primary stream’s ratio of heat capacities
rhop = 19.098; % [kg/m^3] Density of primary stream
% Secondary stream
Secondary_fluid = ‘Air.ppf’;
Ps = 0.1; % [MPa] Pressure of secondary stream
Ts = 20 + 273.15; % [K] Temperature of secondary stream
ks = 1.402; % Secondary stream’s ratio of heat capacities
rhos = 1.189; % [kg/m^3] Density of secondary stream
% Gas constant
R = 0.2871; % [kJ/(kg K)]
% Parameters of ejector (same as in Simscape)
Spt = 1e-4; % [m^2] Throat area
Spn_to_Spt = 3; % Area ratio of nozzle exit to throat
Sm_to_Spt = 8; % Area ratio of mixing chamber exit to throat
eta_p = 0.95; % Efficiency of primary flow through nozzle
eta_s = 0.85; % Efficiency of secondary suction flow
eta_e = 0.88; % Efficiency for primary flow expansion
eta_m = 0.84; % Efficiency for mixing
% Initial guess for Pm
Pm_initial_guess = 0.001; % [MPa]
% Use fsolve to find Pm
options = optimoptions(‘fsolve’, ‘Display’, ‘iter’);
Pm = fsolve(@(Pm) ejector_solver(Pm, Pp, Tp, kp, rhop, Ps, Ts, ks, rhos, R, Spt, Spn_to_Spt, Sm_to_Spt, eta_p, eta_s, eta_e, eta_m), Pm_initial_guess, options);
disp([‘Pm is: ‘, num2str(Pm), ‘ MPa’]);
% Calculate equations with Pm
Ejector_equations
% Critical mode operation
Pm_star = min(Pp,Ps) * (2 / (km+1))^(km / (km-1)); % Threshold that causes choking in both primary and secondary flow
Ejector_equations_star % Same equations to calculate the critical diffuser outlet pressure by replacing Pm with Pm_star
% Evaluate if critical mode operation
if Pd < Pd_star
Pm = Pm_star;
else
Ejector_equations % Repeat equations to save the correct values
end
disp([‘Mm is: ‘, num2str(Mm), ”]);Dear Everyone,
I have written a Matlab script based on the equations of the Ejector in Simscape (https://www.mathworks.com/help/hydro/ref/ejectorg.html). I am not good at using Simscape and I am having difficulties running the Ejector in Simscape.
My script calculates Pm (pressure after mixing ) using fsolve. I have modified the equations a bit as I think γ should be different for the two streams, therefore I have kp (γ of the primary stream) and ks (γ of the secondary stream). I also included an iteration to calculate the stagnation temperatures of the two streams since the documentation of the Ejector states that the block assumes that Tp and Ts (temperatures of primary and secondary streams) are equal to their primary flow stagnation temperature. These temperatures are needed for the calculation of Tm (temperature of mixing). The stagnation temperature depends on Mm (Mach number of mixing) which depends on Tm which in turn depends on the stagnation temperatures.
I am considering a case where the primary stream is CO2 at 1MPa and 20°C and the secondary stream is air at 0.1 MPa and 20°C, and I calculate Pm = 0.0012 MPa and Mm = 0.033. I think these results are wrong, could someone please confirm this? It seems that my solver calculates the same Pm regardless of Pp (primary pressure) and a Pm always close to Ps (secondary pressure).
I am attaching the m files needed to run the script below. "ejector_solver.m". "Ejector_equations_star" uses the same equations as in "Ejector_equations" but replaces Pm with Pm_star to calculate the critical diffuser outlet pressure.
Also, does anyone know how the cross-sectional areas of the three ports are used? They need to be specified for the Ejector in Simscape but I am not sure where they appear in the equations.
I am grateful for any help you can provide.
Best regards,
clearvars; close all; clc;
% Primary stream
Primary_fluid = ‘CO2’;
Pp = 1; % [MPa] Pressure of primary stream
Tp = 20 + 273.15; % [K] Temperature of primary stream
kp = 1.3589; % Primary stream’s ratio of heat capacities
rhop = 19.098; % [kg/m^3] Density of primary stream
% Secondary stream
Secondary_fluid = ‘Air.ppf’;
Ps = 0.1; % [MPa] Pressure of secondary stream
Ts = 20 + 273.15; % [K] Temperature of secondary stream
ks = 1.402; % Secondary stream’s ratio of heat capacities
rhos = 1.189; % [kg/m^3] Density of secondary stream
% Gas constant
R = 0.2871; % [kJ/(kg K)]
% Parameters of ejector (same as in Simscape)
Spt = 1e-4; % [m^2] Throat area
Spn_to_Spt = 3; % Area ratio of nozzle exit to throat
Sm_to_Spt = 8; % Area ratio of mixing chamber exit to throat
eta_p = 0.95; % Efficiency of primary flow through nozzle
eta_s = 0.85; % Efficiency of secondary suction flow
eta_e = 0.88; % Efficiency for primary flow expansion
eta_m = 0.84; % Efficiency for mixing
% Initial guess for Pm
Pm_initial_guess = 0.001; % [MPa]
% Use fsolve to find Pm
options = optimoptions(‘fsolve’, ‘Display’, ‘iter’);
Pm = fsolve(@(Pm) ejector_solver(Pm, Pp, Tp, kp, rhop, Ps, Ts, ks, rhos, R, Spt, Spn_to_Spt, Sm_to_Spt, eta_p, eta_s, eta_e, eta_m), Pm_initial_guess, options);
disp([‘Pm is: ‘, num2str(Pm), ‘ MPa’]);
% Calculate equations with Pm
Ejector_equations
% Critical mode operation
Pm_star = min(Pp,Ps) * (2 / (km+1))^(km / (km-1)); % Threshold that causes choking in both primary and secondary flow
Ejector_equations_star % Same equations to calculate the critical diffuser outlet pressure by replacing Pm with Pm_star
% Evaluate if critical mode operation
if Pd < Pd_star
Pm = Pm_star;
else
Ejector_equations % Repeat equations to save the correct values
end
disp([‘Mm is: ‘, num2str(Mm), ”]); Dear Everyone,
I have written a Matlab script based on the equations of the Ejector in Simscape (https://www.mathworks.com/help/hydro/ref/ejectorg.html). I am not good at using Simscape and I am having difficulties running the Ejector in Simscape.
My script calculates Pm (pressure after mixing ) using fsolve. I have modified the equations a bit as I think γ should be different for the two streams, therefore I have kp (γ of the primary stream) and ks (γ of the secondary stream). I also included an iteration to calculate the stagnation temperatures of the two streams since the documentation of the Ejector states that the block assumes that Tp and Ts (temperatures of primary and secondary streams) are equal to their primary flow stagnation temperature. These temperatures are needed for the calculation of Tm (temperature of mixing). The stagnation temperature depends on Mm (Mach number of mixing) which depends on Tm which in turn depends on the stagnation temperatures.
I am considering a case where the primary stream is CO2 at 1MPa and 20°C and the secondary stream is air at 0.1 MPa and 20°C, and I calculate Pm = 0.0012 MPa and Mm = 0.033. I think these results are wrong, could someone please confirm this? It seems that my solver calculates the same Pm regardless of Pp (primary pressure) and a Pm always close to Ps (secondary pressure).
I am attaching the m files needed to run the script below. "ejector_solver.m". "Ejector_equations_star" uses the same equations as in "Ejector_equations" but replaces Pm with Pm_star to calculate the critical diffuser outlet pressure.
Also, does anyone know how the cross-sectional areas of the three ports are used? They need to be specified for the Ejector in Simscape but I am not sure where they appear in the equations.
I am grateful for any help you can provide.
Best regards,
clearvars; close all; clc;
% Primary stream
Primary_fluid = ‘CO2’;
Pp = 1; % [MPa] Pressure of primary stream
Tp = 20 + 273.15; % [K] Temperature of primary stream
kp = 1.3589; % Primary stream’s ratio of heat capacities
rhop = 19.098; % [kg/m^3] Density of primary stream
% Secondary stream
Secondary_fluid = ‘Air.ppf’;
Ps = 0.1; % [MPa] Pressure of secondary stream
Ts = 20 + 273.15; % [K] Temperature of secondary stream
ks = 1.402; % Secondary stream’s ratio of heat capacities
rhos = 1.189; % [kg/m^3] Density of secondary stream
% Gas constant
R = 0.2871; % [kJ/(kg K)]
% Parameters of ejector (same as in Simscape)
Spt = 1e-4; % [m^2] Throat area
Spn_to_Spt = 3; % Area ratio of nozzle exit to throat
Sm_to_Spt = 8; % Area ratio of mixing chamber exit to throat
eta_p = 0.95; % Efficiency of primary flow through nozzle
eta_s = 0.85; % Efficiency of secondary suction flow
eta_e = 0.88; % Efficiency for primary flow expansion
eta_m = 0.84; % Efficiency for mixing
% Initial guess for Pm
Pm_initial_guess = 0.001; % [MPa]
% Use fsolve to find Pm
options = optimoptions(‘fsolve’, ‘Display’, ‘iter’);
Pm = fsolve(@(Pm) ejector_solver(Pm, Pp, Tp, kp, rhop, Ps, Ts, ks, rhos, R, Spt, Spn_to_Spt, Sm_to_Spt, eta_p, eta_s, eta_e, eta_m), Pm_initial_guess, options);
disp([‘Pm is: ‘, num2str(Pm), ‘ MPa’]);
% Calculate equations with Pm
Ejector_equations
% Critical mode operation
Pm_star = min(Pp,Ps) * (2 / (km+1))^(km / (km-1)); % Threshold that causes choking in both primary and secondary flow
Ejector_equations_star % Same equations to calculate the critical diffuser outlet pressure by replacing Pm with Pm_star
% Evaluate if critical mode operation
if Pd < Pd_star
Pm = Pm_star;
else
Ejector_equations % Repeat equations to save the correct values
end
disp([‘Mm is: ‘, num2str(Mm), ”]); matlab, fsolve, ejector MATLAB Answers — New Questions
Error in legends of subplots using a for loop
I want legends g_1=fr(1), g_1=fr(2), g_1=fr(3) for each plots in each window ha(kk). I am doing some mistake in legends, but couldn’t figured it out. Any suggestions please. Thanks.
[ha, pos]= tight_subplot(4,3,[.1 .15],[.13 .01],[.13 .1]);
fr=([0.1, 0.5, 1]);
[h0, h1]=size(fr);
% for jj=1:h1
for jj=1:3
for kk=1:12
lin={‘–‘,’-.’,’:’};
axes(ha(kk));
x=load(sprintf(‘frq_%d%d.dat’,jj,kk));
x1(jj)=loglog(x(:,33),x(:,kk+5),’linestyle’,lin{jj},’LineWidth’, 2.5);
hold on
ylabel([ha(1),ha(4), ha(7),ha(10)],’Deltaomega_{}’)
xlabel([ha(10), ha(11),ha(12)],’Deltaomega_{o}’)
% legend([x1([1 2 3])],{‘$g_1=fr(%d)$’,jj},’Fontsize’,34,’Location’,’northwest’,’Interpreter’, ‘latex’);
legend([x1([jj])],{‘rm{"$g_1{‘+fr{jj}+’}$"}’},’Fontsize’,34,’Location’,’northwest’,’Interpreter’, ‘latex’);
legend(‘boxoff’)
end
endI want legends g_1=fr(1), g_1=fr(2), g_1=fr(3) for each plots in each window ha(kk). I am doing some mistake in legends, but couldn’t figured it out. Any suggestions please. Thanks.
[ha, pos]= tight_subplot(4,3,[.1 .15],[.13 .01],[.13 .1]);
fr=([0.1, 0.5, 1]);
[h0, h1]=size(fr);
% for jj=1:h1
for jj=1:3
for kk=1:12
lin={‘–‘,’-.’,’:’};
axes(ha(kk));
x=load(sprintf(‘frq_%d%d.dat’,jj,kk));
x1(jj)=loglog(x(:,33),x(:,kk+5),’linestyle’,lin{jj},’LineWidth’, 2.5);
hold on
ylabel([ha(1),ha(4), ha(7),ha(10)],’Deltaomega_{}’)
xlabel([ha(10), ha(11),ha(12)],’Deltaomega_{o}’)
% legend([x1([1 2 3])],{‘$g_1=fr(%d)$’,jj},’Fontsize’,34,’Location’,’northwest’,’Interpreter’, ‘latex’);
legend([x1([jj])],{‘rm{"$g_1{‘+fr{jj}+’}$"}’},’Fontsize’,34,’Location’,’northwest’,’Interpreter’, ‘latex’);
legend(‘boxoff’)
end
end I want legends g_1=fr(1), g_1=fr(2), g_1=fr(3) for each plots in each window ha(kk). I am doing some mistake in legends, but couldn’t figured it out. Any suggestions please. Thanks.
[ha, pos]= tight_subplot(4,3,[.1 .15],[.13 .01],[.13 .1]);
fr=([0.1, 0.5, 1]);
[h0, h1]=size(fr);
% for jj=1:h1
for jj=1:3
for kk=1:12
lin={‘–‘,’-.’,’:’};
axes(ha(kk));
x=load(sprintf(‘frq_%d%d.dat’,jj,kk));
x1(jj)=loglog(x(:,33),x(:,kk+5),’linestyle’,lin{jj},’LineWidth’, 2.5);
hold on
ylabel([ha(1),ha(4), ha(7),ha(10)],’Deltaomega_{}’)
xlabel([ha(10), ha(11),ha(12)],’Deltaomega_{o}’)
% legend([x1([1 2 3])],{‘$g_1=fr(%d)$’,jj},’Fontsize’,34,’Location’,’northwest’,’Interpreter’, ‘latex’);
legend([x1([jj])],{‘rm{"$g_1{‘+fr{jj}+’}$"}’},’Fontsize’,34,’Location’,’northwest’,’Interpreter’, ‘latex’);
legend(‘boxoff’)
end
end plotting, subplot, legend, for loop MATLAB Answers — New Questions
why is 2D deformation plot in pdeplot samller with larger DefromationScaleFactor
I’ve used both pdeplot3d and pdeplot to show deformation after structure analysis. The DeformationScaleFactor is used to scale the distortion of the final picture plotted. I’ve noticed for pdeplot3d, a larger DeformationScaleFacotor means larger distortion. The online documents can clearly show it, https://ww2.mathworks.cn/help/pde/ug/pdeplot3d.html?s_tid=doc_ta#d126e109923. However, in 2d pdeplot, a larger DeformationScaleFactor will result in a smaller distortion. https://ww2.mathworks.cn/help/pde/ug/pdeplot.html?searchHighlight=pdeplot&s_tid=srchtitle_support_results_1_pdeplot. Is there any explaination on this comparison?
I caputured two pictures both function for convinience.
pdeplot3d case: larger DeformationScaleFactor larger distortion:
pdeplot case: larger DeformationScaleFactor smaller distortion:I’ve used both pdeplot3d and pdeplot to show deformation after structure analysis. The DeformationScaleFactor is used to scale the distortion of the final picture plotted. I’ve noticed for pdeplot3d, a larger DeformationScaleFacotor means larger distortion. The online documents can clearly show it, https://ww2.mathworks.cn/help/pde/ug/pdeplot3d.html?s_tid=doc_ta#d126e109923. However, in 2d pdeplot, a larger DeformationScaleFactor will result in a smaller distortion. https://ww2.mathworks.cn/help/pde/ug/pdeplot.html?searchHighlight=pdeplot&s_tid=srchtitle_support_results_1_pdeplot. Is there any explaination on this comparison?
I caputured two pictures both function for convinience.
pdeplot3d case: larger DeformationScaleFactor larger distortion:
pdeplot case: larger DeformationScaleFactor smaller distortion: I’ve used both pdeplot3d and pdeplot to show deformation after structure analysis. The DeformationScaleFactor is used to scale the distortion of the final picture plotted. I’ve noticed for pdeplot3d, a larger DeformationScaleFacotor means larger distortion. The online documents can clearly show it, https://ww2.mathworks.cn/help/pde/ug/pdeplot3d.html?s_tid=doc_ta#d126e109923. However, in 2d pdeplot, a larger DeformationScaleFactor will result in a smaller distortion. https://ww2.mathworks.cn/help/pde/ug/pdeplot.html?searchHighlight=pdeplot&s_tid=srchtitle_support_results_1_pdeplot. Is there any explaination on this comparison?
I caputured two pictures both function for convinience.
pdeplot3d case: larger DeformationScaleFactor larger distortion:
pdeplot case: larger DeformationScaleFactor smaller distortion: deformationscalefactor, pdeplot, pdeplot3d MATLAB Answers — New Questions
Tiledlayout: Make Plots of unequal width
Hello,
I want to use tiledlayout to place multiple graphs of unequal width. An example of what I’m trying to do is below. Using the figure command only seems to edit the entire box and I’m not sure how to make the tiledlayout command do what I want
Current figure:
Desired appearance (expertly edited using MS Paint)
Example code:
figure(‘Units’,’normalized’,’Position’,[0.5,0.4,.5,.5]);
tiledlayout(1,2,’TileSpacing’,’Compact’,’Padding’,’Compact’)
nexttile
plot(foo,bar)
%formatting stuff
nexttile
plot (foo2,bar2)
%formatting stuffHello,
I want to use tiledlayout to place multiple graphs of unequal width. An example of what I’m trying to do is below. Using the figure command only seems to edit the entire box and I’m not sure how to make the tiledlayout command do what I want
Current figure:
Desired appearance (expertly edited using MS Paint)
Example code:
figure(‘Units’,’normalized’,’Position’,[0.5,0.4,.5,.5]);
tiledlayout(1,2,’TileSpacing’,’Compact’,’Padding’,’Compact’)
nexttile
plot(foo,bar)
%formatting stuff
nexttile
plot (foo2,bar2)
%formatting stuff Hello,
I want to use tiledlayout to place multiple graphs of unequal width. An example of what I’m trying to do is below. Using the figure command only seems to edit the entire box and I’m not sure how to make the tiledlayout command do what I want
Current figure:
Desired appearance (expertly edited using MS Paint)
Example code:
figure(‘Units’,’normalized’,’Position’,[0.5,0.4,.5,.5]);
tiledlayout(1,2,’TileSpacing’,’Compact’,’Padding’,’Compact’)
nexttile
plot(foo,bar)
%formatting stuff
nexttile
plot (foo2,bar2)
%formatting stuff tiledlayout, plot dimensions MATLAB Answers — New Questions
PID Controller Gain adjust
Hallo Jungs bitte jemand mir helfen?: habe einen pid-Regler für ein Selfdriving car entwickeln. das Problem ist das Fahrzeug fährt nicht in Centerline wie geplann und nach änderung der Strecke, wird der Fehler noch schlimer. kann jemand mir helfen?
function LateralLongitudinal_Controller(obj, cte)
kp_lat = 0.08; % Parameter für laterale Regelung
kd_lat = 0.8;
ki_lat = 0.000002;
kp_lon = 0.1; % Parameter für longitudinale Regelung
kd_lon = 0.01;
ki_lon = 0.000001;
dcte = cte – obj.old_cte;
obj.cte_intergral = obj.cte_intergral + cte;
% Anti-Windup für den integralen Anteil
obj.cte_intergral = max(-obj.steering_angle_limit / ki_lat, min(obj.steering_angle_limit / ki_lat, obj.cte_intergral));
obj.old_cte = cte;
% Lateral Control (quer)
steering = kp_lat * cte + kd_lat * dcte + ki_lat * obj.cte_intergral;
% Begrenzen Sie den Lenkwinkel
steering = max(-obj.steering_angle_limit, min(obj.steering_angle_limit, steering));
% Longitudinal Control (längs)
desired_velocity = obj.max_velocity; % Setzen Sie die gewünschte Geschwindigkeit
velocity_error = desired_velocity – obj.states(4);
% Fügen Sie die max_acceleration-Eigenschaft hinzu
max_acceleration = 10.0; % Setzen Sie hier den gewünschten maximalen Beschleunigungswert ein
% Reduziere die Geschwindigkeit in der Nähe von Kurven
curvature_threshold = 0.4; % Setzen Sie den Krümmungsschwellenwert ein
if abs(cte) > curvature_threshold
desired_velocity = 10 * obj.max_velocity; % Reduziere die Geschwindigkeit in der Nähe von Kurven
end
acceleration = kp_lon * velocity_error + kd_lon * obj.states(4) + ki_lon * sum(obj.states(1:4));
% Begrenzen Sie die Beschleunigung
acceleration = max(-max_acceleration, min(max_acceleration, acceleration));
control_signal = [steering, acceleration];
obj.update_input(control_signal);
endHallo Jungs bitte jemand mir helfen?: habe einen pid-Regler für ein Selfdriving car entwickeln. das Problem ist das Fahrzeug fährt nicht in Centerline wie geplann und nach änderung der Strecke, wird der Fehler noch schlimer. kann jemand mir helfen?
function LateralLongitudinal_Controller(obj, cte)
kp_lat = 0.08; % Parameter für laterale Regelung
kd_lat = 0.8;
ki_lat = 0.000002;
kp_lon = 0.1; % Parameter für longitudinale Regelung
kd_lon = 0.01;
ki_lon = 0.000001;
dcte = cte – obj.old_cte;
obj.cte_intergral = obj.cte_intergral + cte;
% Anti-Windup für den integralen Anteil
obj.cte_intergral = max(-obj.steering_angle_limit / ki_lat, min(obj.steering_angle_limit / ki_lat, obj.cte_intergral));
obj.old_cte = cte;
% Lateral Control (quer)
steering = kp_lat * cte + kd_lat * dcte + ki_lat * obj.cte_intergral;
% Begrenzen Sie den Lenkwinkel
steering = max(-obj.steering_angle_limit, min(obj.steering_angle_limit, steering));
% Longitudinal Control (längs)
desired_velocity = obj.max_velocity; % Setzen Sie die gewünschte Geschwindigkeit
velocity_error = desired_velocity – obj.states(4);
% Fügen Sie die max_acceleration-Eigenschaft hinzu
max_acceleration = 10.0; % Setzen Sie hier den gewünschten maximalen Beschleunigungswert ein
% Reduziere die Geschwindigkeit in der Nähe von Kurven
curvature_threshold = 0.4; % Setzen Sie den Krümmungsschwellenwert ein
if abs(cte) > curvature_threshold
desired_velocity = 10 * obj.max_velocity; % Reduziere die Geschwindigkeit in der Nähe von Kurven
end
acceleration = kp_lon * velocity_error + kd_lon * obj.states(4) + ki_lon * sum(obj.states(1:4));
% Begrenzen Sie die Beschleunigung
acceleration = max(-max_acceleration, min(max_acceleration, acceleration));
control_signal = [steering, acceleration];
obj.update_input(control_signal);
end Hallo Jungs bitte jemand mir helfen?: habe einen pid-Regler für ein Selfdriving car entwickeln. das Problem ist das Fahrzeug fährt nicht in Centerline wie geplann und nach änderung der Strecke, wird der Fehler noch schlimer. kann jemand mir helfen?
function LateralLongitudinal_Controller(obj, cte)
kp_lat = 0.08; % Parameter für laterale Regelung
kd_lat = 0.8;
ki_lat = 0.000002;
kp_lon = 0.1; % Parameter für longitudinale Regelung
kd_lon = 0.01;
ki_lon = 0.000001;
dcte = cte – obj.old_cte;
obj.cte_intergral = obj.cte_intergral + cte;
% Anti-Windup für den integralen Anteil
obj.cte_intergral = max(-obj.steering_angle_limit / ki_lat, min(obj.steering_angle_limit / ki_lat, obj.cte_intergral));
obj.old_cte = cte;
% Lateral Control (quer)
steering = kp_lat * cte + kd_lat * dcte + ki_lat * obj.cte_intergral;
% Begrenzen Sie den Lenkwinkel
steering = max(-obj.steering_angle_limit, min(obj.steering_angle_limit, steering));
% Longitudinal Control (längs)
desired_velocity = obj.max_velocity; % Setzen Sie die gewünschte Geschwindigkeit
velocity_error = desired_velocity – obj.states(4);
% Fügen Sie die max_acceleration-Eigenschaft hinzu
max_acceleration = 10.0; % Setzen Sie hier den gewünschten maximalen Beschleunigungswert ein
% Reduziere die Geschwindigkeit in der Nähe von Kurven
curvature_threshold = 0.4; % Setzen Sie den Krümmungsschwellenwert ein
if abs(cte) > curvature_threshold
desired_velocity = 10 * obj.max_velocity; % Reduziere die Geschwindigkeit in der Nähe von Kurven
end
acceleration = kp_lon * velocity_error + kd_lon * obj.states(4) + ki_lon * sum(obj.states(1:4));
% Begrenzen Sie die Beschleunigung
acceleration = max(-max_acceleration, min(max_acceleration, acceleration));
control_signal = [steering, acceleration];
obj.update_input(control_signal);
end pid controller MATLAB Answers — New Questions
How to move colorbar in scatter3 plot and keep it inside the figure
After adding title to the colorbar of a scatter3 plot, I realized the formatting is all wonky.
Looking online, I moved the colorbar to southoutside, and was able to move the colorbar by setting its second position, see code below, but it simply moves the colorbar out of the window instead and can no longer be seen.
Based on another answer, I tried to move the axes of the scatter3 plot, since in that case, moving the axes forced the figure window to resize, but it failed – scatter3’s axes doesn’t seem to have position property, which makes sense, given the type of figure.
So I am at a loss. I could move the parts manually, and then resize the main plot area, but I would love to be able to do it with the script since I would need to process many figures like this. Does anyone have any suggestions?
importdata(‘GNDout.mat’);
x = GNDout(:,1);
y = GNDout(:,2);
z = GNDout(:,3);
value2 = GNDout(:,17)-min(GNDout(:,17));
figure;
S = 50;
scatter3(x,y,z,S,value2/1e14,’filled’);
xlabel(‘x’);
ylabel(‘y’);
zlabel(‘z’);
axis equal;
cb = colorbar(‘Location’,’Southoutside’);
cb.Position(2) = cb.Position(2)-0.5;
title(cb, ‘rho_{GND} [10^{14} m^{-2}]’);
Attached is the data GNDout. Thanks in advance!After adding title to the colorbar of a scatter3 plot, I realized the formatting is all wonky.
Looking online, I moved the colorbar to southoutside, and was able to move the colorbar by setting its second position, see code below, but it simply moves the colorbar out of the window instead and can no longer be seen.
Based on another answer, I tried to move the axes of the scatter3 plot, since in that case, moving the axes forced the figure window to resize, but it failed – scatter3’s axes doesn’t seem to have position property, which makes sense, given the type of figure.
So I am at a loss. I could move the parts manually, and then resize the main plot area, but I would love to be able to do it with the script since I would need to process many figures like this. Does anyone have any suggestions?
importdata(‘GNDout.mat’);
x = GNDout(:,1);
y = GNDout(:,2);
z = GNDout(:,3);
value2 = GNDout(:,17)-min(GNDout(:,17));
figure;
S = 50;
scatter3(x,y,z,S,value2/1e14,’filled’);
xlabel(‘x’);
ylabel(‘y’);
zlabel(‘z’);
axis equal;
cb = colorbar(‘Location’,’Southoutside’);
cb.Position(2) = cb.Position(2)-0.5;
title(cb, ‘rho_{GND} [10^{14} m^{-2}]’);
Attached is the data GNDout. Thanks in advance! After adding title to the colorbar of a scatter3 plot, I realized the formatting is all wonky.
Looking online, I moved the colorbar to southoutside, and was able to move the colorbar by setting its second position, see code below, but it simply moves the colorbar out of the window instead and can no longer be seen.
Based on another answer, I tried to move the axes of the scatter3 plot, since in that case, moving the axes forced the figure window to resize, but it failed – scatter3’s axes doesn’t seem to have position property, which makes sense, given the type of figure.
So I am at a loss. I could move the parts manually, and then resize the main plot area, but I would love to be able to do it with the script since I would need to process many figures like this. Does anyone have any suggestions?
importdata(‘GNDout.mat’);
x = GNDout(:,1);
y = GNDout(:,2);
z = GNDout(:,3);
value2 = GNDout(:,17)-min(GNDout(:,17));
figure;
S = 50;
scatter3(x,y,z,S,value2/1e14,’filled’);
xlabel(‘x’);
ylabel(‘y’);
zlabel(‘z’);
axis equal;
cb = colorbar(‘Location’,’Southoutside’);
cb.Position(2) = cb.Position(2)-0.5;
title(cb, ‘rho_{GND} [10^{14} m^{-2}]’);
Attached is the data GNDout. Thanks in advance! plotting, figure MATLAB Answers — New Questions
The perpendicular point is not on the proposed line.
I would like to ask what is wrong with my code that the green line is not on the fit line?
Now I have to fit two lines to the given coordinates and calculate their perpendicular distance from the center of the circle. Then their slopes will be based on the data_line1.
% 基準綫坐標
data_line1 = readtable("基準綫.csv");
data_line2 = readtable("基準綫2.csv");
x_line1 = data_line1{7:end, 1};
y_line1 = data_line1{7:end, 2};
x_line2 = data_line2{7:end, 1};
y_line2 = data_line2{7:end, 2};
% 圓心坐標
center_x = 37.5;
center_y = 37.5;
% 擬合第一條綫
x1 = x_line1;
y1 = y_line1;
p_line = polyfit(x1, y1, 1);
slope = p_line(1);
intercept = p_line(2);
A = slope;
B = -1;
C = intercept;
x_foot = (center_x – slope * (center_y – intercept)) / (1 + slope^2);
y_foot = slope * x_foot + intercept;
distance = abs(A * center_x + B * center_y + C) / sqrt(A^2 + B^2);
disp(‘垂直距離1:’);
disp(distance);
% 繪製結果
figure;
hold on;
plot(x1, y1, ‘bo’, ‘DisplayName’, ‘原始數據1’); % 原始數據點
plot(center_x, center_y, ‘rx’, ‘MarkerSize’, 10, ‘DisplayName’, ‘圓心’); % 圓心
% 繪製擬合直線
fitted_x = linspace(min(x_line1), max(x_line1), 100);
fitted_y = polyval(p_line, fitted_x);
plot(fitted_x, fitted_y, ‘k–‘, ‘DisplayName’, ‘擬合直線1’);
% 繪製垂直距離線
plot([center_x, x_foot], [center_y, y_foot], ‘r-‘, ‘DisplayName’, ‘垂直距離1’);
% 擬合第二條綫
x2 = x_line2;
y2 = y_line2;
p2_line = polyfit(x2, y2, 1);
intercept_2 = p2_line(2);
C2 = intercept_2;
x_foot_2 = (center_x – slope * (center_y – intercept_2)) / (1 + slope^2);
y_foot_2 = slope * x_foot_2 + intercept_2;
distance_2 = abs(A * center_x + B * center_y + C2) / sqrt(A^2 + B^2);
disp(‘垂直距離2:’);
disp(distance_2);
% 繪製第二條線和垂直距離線
plot(x2, y2, ‘go’, ‘DisplayName’, ‘原始數據2’); % 原始數據點2
fitted_y2 = polyval(p2_line, fitted_x);
plot(fitted_x, fitted_y2, ‘b–‘, ‘DisplayName’, ‘擬合直線2’);
plot([center_x, x_foot_2], [center_y, y_foot_2], ‘g-‘, ‘DisplayName’, ‘垂直距離2’);
legend;
xlabel(‘X軸’);
ylabel(‘Y軸’);
title(‘從圓心到擬合直綫的垂直距離’);
grid on;
hold off;I would like to ask what is wrong with my code that the green line is not on the fit line?
Now I have to fit two lines to the given coordinates and calculate their perpendicular distance from the center of the circle. Then their slopes will be based on the data_line1.
% 基準綫坐標
data_line1 = readtable("基準綫.csv");
data_line2 = readtable("基準綫2.csv");
x_line1 = data_line1{7:end, 1};
y_line1 = data_line1{7:end, 2};
x_line2 = data_line2{7:end, 1};
y_line2 = data_line2{7:end, 2};
% 圓心坐標
center_x = 37.5;
center_y = 37.5;
% 擬合第一條綫
x1 = x_line1;
y1 = y_line1;
p_line = polyfit(x1, y1, 1);
slope = p_line(1);
intercept = p_line(2);
A = slope;
B = -1;
C = intercept;
x_foot = (center_x – slope * (center_y – intercept)) / (1 + slope^2);
y_foot = slope * x_foot + intercept;
distance = abs(A * center_x + B * center_y + C) / sqrt(A^2 + B^2);
disp(‘垂直距離1:’);
disp(distance);
% 繪製結果
figure;
hold on;
plot(x1, y1, ‘bo’, ‘DisplayName’, ‘原始數據1’); % 原始數據點
plot(center_x, center_y, ‘rx’, ‘MarkerSize’, 10, ‘DisplayName’, ‘圓心’); % 圓心
% 繪製擬合直線
fitted_x = linspace(min(x_line1), max(x_line1), 100);
fitted_y = polyval(p_line, fitted_x);
plot(fitted_x, fitted_y, ‘k–‘, ‘DisplayName’, ‘擬合直線1’);
% 繪製垂直距離線
plot([center_x, x_foot], [center_y, y_foot], ‘r-‘, ‘DisplayName’, ‘垂直距離1’);
% 擬合第二條綫
x2 = x_line2;
y2 = y_line2;
p2_line = polyfit(x2, y2, 1);
intercept_2 = p2_line(2);
C2 = intercept_2;
x_foot_2 = (center_x – slope * (center_y – intercept_2)) / (1 + slope^2);
y_foot_2 = slope * x_foot_2 + intercept_2;
distance_2 = abs(A * center_x + B * center_y + C2) / sqrt(A^2 + B^2);
disp(‘垂直距離2:’);
disp(distance_2);
% 繪製第二條線和垂直距離線
plot(x2, y2, ‘go’, ‘DisplayName’, ‘原始數據2’); % 原始數據點2
fitted_y2 = polyval(p2_line, fitted_x);
plot(fitted_x, fitted_y2, ‘b–‘, ‘DisplayName’, ‘擬合直線2’);
plot([center_x, x_foot_2], [center_y, y_foot_2], ‘g-‘, ‘DisplayName’, ‘垂直距離2’);
legend;
xlabel(‘X軸’);
ylabel(‘Y軸’);
title(‘從圓心到擬合直綫的垂直距離’);
grid on;
hold off; I would like to ask what is wrong with my code that the green line is not on the fit line?
Now I have to fit two lines to the given coordinates and calculate their perpendicular distance from the center of the circle. Then their slopes will be based on the data_line1.
% 基準綫坐標
data_line1 = readtable("基準綫.csv");
data_line2 = readtable("基準綫2.csv");
x_line1 = data_line1{7:end, 1};
y_line1 = data_line1{7:end, 2};
x_line2 = data_line2{7:end, 1};
y_line2 = data_line2{7:end, 2};
% 圓心坐標
center_x = 37.5;
center_y = 37.5;
% 擬合第一條綫
x1 = x_line1;
y1 = y_line1;
p_line = polyfit(x1, y1, 1);
slope = p_line(1);
intercept = p_line(2);
A = slope;
B = -1;
C = intercept;
x_foot = (center_x – slope * (center_y – intercept)) / (1 + slope^2);
y_foot = slope * x_foot + intercept;
distance = abs(A * center_x + B * center_y + C) / sqrt(A^2 + B^2);
disp(‘垂直距離1:’);
disp(distance);
% 繪製結果
figure;
hold on;
plot(x1, y1, ‘bo’, ‘DisplayName’, ‘原始數據1’); % 原始數據點
plot(center_x, center_y, ‘rx’, ‘MarkerSize’, 10, ‘DisplayName’, ‘圓心’); % 圓心
% 繪製擬合直線
fitted_x = linspace(min(x_line1), max(x_line1), 100);
fitted_y = polyval(p_line, fitted_x);
plot(fitted_x, fitted_y, ‘k–‘, ‘DisplayName’, ‘擬合直線1’);
% 繪製垂直距離線
plot([center_x, x_foot], [center_y, y_foot], ‘r-‘, ‘DisplayName’, ‘垂直距離1’);
% 擬合第二條綫
x2 = x_line2;
y2 = y_line2;
p2_line = polyfit(x2, y2, 1);
intercept_2 = p2_line(2);
C2 = intercept_2;
x_foot_2 = (center_x – slope * (center_y – intercept_2)) / (1 + slope^2);
y_foot_2 = slope * x_foot_2 + intercept_2;
distance_2 = abs(A * center_x + B * center_y + C2) / sqrt(A^2 + B^2);
disp(‘垂直距離2:’);
disp(distance_2);
% 繪製第二條線和垂直距離線
plot(x2, y2, ‘go’, ‘DisplayName’, ‘原始數據2’); % 原始數據點2
fitted_y2 = polyval(p2_line, fitted_x);
plot(fitted_x, fitted_y2, ‘b–‘, ‘DisplayName’, ‘擬合直線2’);
plot([center_x, x_foot_2], [center_y, y_foot_2], ‘g-‘, ‘DisplayName’, ‘垂直距離2’);
legend;
xlabel(‘X軸’);
ylabel(‘Y軸’);
title(‘從圓心到擬合直綫的垂直距離’);
grid on;
hold off; polyfit, line MATLAB Answers — New Questions
Best analysis to show how EEG ranges are similar
Hello,
Hoping someone can help! Have samples from EEG from multiple patients over multiple points in time that I want to visually show and quantiatively show and prove over time that these patterns are the same. I am thinking of using a wavelet transform over time. The question is can i amalgamate an entire EEG signal to 1 plot. Or would it be better to isolate this pattern at one electrode and compare between patients?
Thank you!Hello,
Hoping someone can help! Have samples from EEG from multiple patients over multiple points in time that I want to visually show and quantiatively show and prove over time that these patterns are the same. I am thinking of using a wavelet transform over time. The question is can i amalgamate an entire EEG signal to 1 plot. Or would it be better to isolate this pattern at one electrode and compare between patients?
Thank you! Hello,
Hoping someone can help! Have samples from EEG from multiple patients over multiple points in time that I want to visually show and quantiatively show and prove over time that these patterns are the same. I am thinking of using a wavelet transform over time. The question is can i amalgamate an entire EEG signal to 1 plot. Or would it be better to isolate this pattern at one electrode and compare between patients?
Thank you! eeg, medical MATLAB Answers — New Questions
Value to differentiate is not traced. It must be a traced real dlarray scalar. Use dlgradient inside a function called by dlfeval to trace the variables.
Hello, I am working on customizing the loss function to minimize dimensionality by maximizing the Bhattacharyya distance distance.
But it came up with a error shown as:
Incorrect use of dlarray/dlgradient
The requested value was not tracked. It must be a real dlarray scalar for tracking. Please use dlgradient to track variables in the function called by dlfestival.
% Parameter settings
M = 10; % Dimension of input features
N = 50; % Number of samples per class
numEpochs = 100;
learnRate = 0.01;
% Generate example data
X = rand(2*N, M);
X(1:N, 🙂 = X(1:N, 🙂 + 1; % Data for class A
X(N+1:end, 🙂 = X(N+1:end, 🙂 – 1; % Data for class B
% Define the neural network
layers = [
featureInputLayer(M, ‘Normalization’, ‘none’)
fullyConnectedLayer(10)
reluLayer
fullyConnectedLayer(3)
];
dlnet = dlnetwork(layerGraph(layers));
% Custom training loop
for epoch = 1:numEpochs
dlX = dlarray(X’, ‘CB’); % Transpose input data to match network’s expected format
[gradients, loss] = dlfeval(@modelGradients, dlnet, dlX, N);
dlnet = dlupdate(@sgdmupdate, dlnet, gradients, learnRate);
disp([‘Epoch ‘ num2str(epoch) ‘, Loss: ‘ num2str(extractdata(loss))]);
end
% Testing phase
X_test = rand(N, M); % Assume test data is randomly generated
dlX_test = dlarray(X_test’, ‘CB’); % Transpose input data to match network’s expected format
Y_test = predict(dlnet, dlX_test);
disp(‘Dimensionality reduction results during testing:’);
disp(extractdata(Y_test)’);
% Custom loss function
function loss = customLoss(Y, N)
YA = extractdata(Y(:, 1:N))’;
YB = extractdata(Y(:, N+1:end))’;
muA = mean(YA);
muB = mean(YB);
covA = cov(YA);
covB = cov(YB);
covMean = (covA + covB) / 2;
d = 0.25 * (muA – muB) / covMean * (muA – muB)’ + 0.5 * log(det(covMean) / sqrt(det(covA) * det(covB)));
loss = -d; % Maximize Bhattacharyya distance
loss = dlarray(loss); % Ensure loss is a tracked dlarray scalar
end
% Model gradient function
function [gradients, loss] = modelGradients(dlnet, dlX, N)
Y = forward(dlnet, dlX);
loss = customLoss(Y, N);
gradients = dlgradient(loss, dlnet.Learnables);
end
% Update function
function param = sgdmupdate(param, grad, learnRate)
param = param – learnRate * grad;
endHello, I am working on customizing the loss function to minimize dimensionality by maximizing the Bhattacharyya distance distance.
But it came up with a error shown as:
Incorrect use of dlarray/dlgradient
The requested value was not tracked. It must be a real dlarray scalar for tracking. Please use dlgradient to track variables in the function called by dlfestival.
% Parameter settings
M = 10; % Dimension of input features
N = 50; % Number of samples per class
numEpochs = 100;
learnRate = 0.01;
% Generate example data
X = rand(2*N, M);
X(1:N, 🙂 = X(1:N, 🙂 + 1; % Data for class A
X(N+1:end, 🙂 = X(N+1:end, 🙂 – 1; % Data for class B
% Define the neural network
layers = [
featureInputLayer(M, ‘Normalization’, ‘none’)
fullyConnectedLayer(10)
reluLayer
fullyConnectedLayer(3)
];
dlnet = dlnetwork(layerGraph(layers));
% Custom training loop
for epoch = 1:numEpochs
dlX = dlarray(X’, ‘CB’); % Transpose input data to match network’s expected format
[gradients, loss] = dlfeval(@modelGradients, dlnet, dlX, N);
dlnet = dlupdate(@sgdmupdate, dlnet, gradients, learnRate);
disp([‘Epoch ‘ num2str(epoch) ‘, Loss: ‘ num2str(extractdata(loss))]);
end
% Testing phase
X_test = rand(N, M); % Assume test data is randomly generated
dlX_test = dlarray(X_test’, ‘CB’); % Transpose input data to match network’s expected format
Y_test = predict(dlnet, dlX_test);
disp(‘Dimensionality reduction results during testing:’);
disp(extractdata(Y_test)’);
% Custom loss function
function loss = customLoss(Y, N)
YA = extractdata(Y(:, 1:N))’;
YB = extractdata(Y(:, N+1:end))’;
muA = mean(YA);
muB = mean(YB);
covA = cov(YA);
covB = cov(YB);
covMean = (covA + covB) / 2;
d = 0.25 * (muA – muB) / covMean * (muA – muB)’ + 0.5 * log(det(covMean) / sqrt(det(covA) * det(covB)));
loss = -d; % Maximize Bhattacharyya distance
loss = dlarray(loss); % Ensure loss is a tracked dlarray scalar
end
% Model gradient function
function [gradients, loss] = modelGradients(dlnet, dlX, N)
Y = forward(dlnet, dlX);
loss = customLoss(Y, N);
gradients = dlgradient(loss, dlnet.Learnables);
end
% Update function
function param = sgdmupdate(param, grad, learnRate)
param = param – learnRate * grad;
end Hello, I am working on customizing the loss function to minimize dimensionality by maximizing the Bhattacharyya distance distance.
But it came up with a error shown as:
Incorrect use of dlarray/dlgradient
The requested value was not tracked. It must be a real dlarray scalar for tracking. Please use dlgradient to track variables in the function called by dlfestival.
% Parameter settings
M = 10; % Dimension of input features
N = 50; % Number of samples per class
numEpochs = 100;
learnRate = 0.01;
% Generate example data
X = rand(2*N, M);
X(1:N, 🙂 = X(1:N, 🙂 + 1; % Data for class A
X(N+1:end, 🙂 = X(N+1:end, 🙂 – 1; % Data for class B
% Define the neural network
layers = [
featureInputLayer(M, ‘Normalization’, ‘none’)
fullyConnectedLayer(10)
reluLayer
fullyConnectedLayer(3)
];
dlnet = dlnetwork(layerGraph(layers));
% Custom training loop
for epoch = 1:numEpochs
dlX = dlarray(X’, ‘CB’); % Transpose input data to match network’s expected format
[gradients, loss] = dlfeval(@modelGradients, dlnet, dlX, N);
dlnet = dlupdate(@sgdmupdate, dlnet, gradients, learnRate);
disp([‘Epoch ‘ num2str(epoch) ‘, Loss: ‘ num2str(extractdata(loss))]);
end
% Testing phase
X_test = rand(N, M); % Assume test data is randomly generated
dlX_test = dlarray(X_test’, ‘CB’); % Transpose input data to match network’s expected format
Y_test = predict(dlnet, dlX_test);
disp(‘Dimensionality reduction results during testing:’);
disp(extractdata(Y_test)’);
% Custom loss function
function loss = customLoss(Y, N)
YA = extractdata(Y(:, 1:N))’;
YB = extractdata(Y(:, N+1:end))’;
muA = mean(YA);
muB = mean(YB);
covA = cov(YA);
covB = cov(YB);
covMean = (covA + covB) / 2;
d = 0.25 * (muA – muB) / covMean * (muA – muB)’ + 0.5 * log(det(covMean) / sqrt(det(covA) * det(covB)));
loss = -d; % Maximize Bhattacharyya distance
loss = dlarray(loss); % Ensure loss is a tracked dlarray scalar
end
% Model gradient function
function [gradients, loss] = modelGradients(dlnet, dlX, N)
Y = forward(dlnet, dlX);
loss = customLoss(Y, N);
gradients = dlgradient(loss, dlnet.Learnables);
end
% Update function
function param = sgdmupdate(param, grad, learnRate)
param = param – learnRate * grad;
end deep learning MATLAB Answers — New Questions
Incorrect use of dlarray/dlgradient
Hello, I am working on customizing the loss function to minimize dimensionality by maximizing the Bhattacharyya distance distance.
But it came up with a error shown as:
Incorrect use of dlarray/dlgradient
The requested value was not tracked. It must be a real dlarray scalar for tracking. Please use dlgradient to track variables in the function called by dlfestival.
% Parameter settings
M = 10; % Dimension of input features
N = 50; % Number of samples per class
numEpochs = 100;
learnRate = 0.01;
% Generate example data
X = rand(2*N, M);
X(1:N, 🙂 = X(1:N, 🙂 + 1; % Data for class A
X(N+1:end, 🙂 = X(N+1:end, 🙂 – 1; % Data for class B
% Define the neural network
layers = [
featureInputLayer(M, ‘Normalization’, ‘none’)
fullyConnectedLayer(10)
reluLayer
fullyConnectedLayer(3)
];
dlnet = dlnetwork(layerGraph(layers));
% Custom training loop
for epoch = 1:numEpochs
dlX = dlarray(X’, ‘CB’); % Transpose input data to match network’s expected format
[gradients, loss] = dlfeval(@modelGradients, dlnet, dlX, N);
dlnet = dlupdate(@sgdmupdate, dlnet, gradients, learnRate);
disp([‘Epoch ‘ num2str(epoch) ‘, Loss: ‘ num2str(extractdata(loss))]);
end
% Testing phase
X_test = rand(N, M); % Assume test data is randomly generated
dlX_test = dlarray(X_test’, ‘CB’); % Transpose input data to match network’s expected format
Y_test = predict(dlnet, dlX_test);
disp(‘Dimensionality reduction results during testing:’);
disp(extractdata(Y_test)’);
% Custom loss function
function loss = customLoss(Y, N)
YA = extractdata(Y(:, 1:N))’;
YB = extractdata(Y(:, N+1:end))’;
muA = mean(YA);
muB = mean(YB);
covA = cov(YA);
covB = cov(YB);
covMean = (covA + covB) / 2;
d = 0.25 * (muA – muB) / covMean * (muA – muB)’ + 0.5 * log(det(covMean) / sqrt(det(covA) * det(covB)));
loss = -d; % Maximize Bhattacharyya distance
loss = dlarray(loss); % Ensure loss is a tracked dlarray scalar
end
% Model gradient function
function [gradients, loss] = modelGradients(dlnet, dlX, N)
Y = forward(dlnet, dlX);
loss = customLoss(Y, N);
gradients = dlgradient(loss, dlnet.Learnables);
end
% Update function
function param = sgdmupdate(param, grad, learnRate)
param = param – learnRate * grad;
endHello, I am working on customizing the loss function to minimize dimensionality by maximizing the Bhattacharyya distance distance.
But it came up with a error shown as:
Incorrect use of dlarray/dlgradient
The requested value was not tracked. It must be a real dlarray scalar for tracking. Please use dlgradient to track variables in the function called by dlfestival.
% Parameter settings
M = 10; % Dimension of input features
N = 50; % Number of samples per class
numEpochs = 100;
learnRate = 0.01;
% Generate example data
X = rand(2*N, M);
X(1:N, 🙂 = X(1:N, 🙂 + 1; % Data for class A
X(N+1:end, 🙂 = X(N+1:end, 🙂 – 1; % Data for class B
% Define the neural network
layers = [
featureInputLayer(M, ‘Normalization’, ‘none’)
fullyConnectedLayer(10)
reluLayer
fullyConnectedLayer(3)
];
dlnet = dlnetwork(layerGraph(layers));
% Custom training loop
for epoch = 1:numEpochs
dlX = dlarray(X’, ‘CB’); % Transpose input data to match network’s expected format
[gradients, loss] = dlfeval(@modelGradients, dlnet, dlX, N);
dlnet = dlupdate(@sgdmupdate, dlnet, gradients, learnRate);
disp([‘Epoch ‘ num2str(epoch) ‘, Loss: ‘ num2str(extractdata(loss))]);
end
% Testing phase
X_test = rand(N, M); % Assume test data is randomly generated
dlX_test = dlarray(X_test’, ‘CB’); % Transpose input data to match network’s expected format
Y_test = predict(dlnet, dlX_test);
disp(‘Dimensionality reduction results during testing:’);
disp(extractdata(Y_test)’);
% Custom loss function
function loss = customLoss(Y, N)
YA = extractdata(Y(:, 1:N))’;
YB = extractdata(Y(:, N+1:end))’;
muA = mean(YA);
muB = mean(YB);
covA = cov(YA);
covB = cov(YB);
covMean = (covA + covB) / 2;
d = 0.25 * (muA – muB) / covMean * (muA – muB)’ + 0.5 * log(det(covMean) / sqrt(det(covA) * det(covB)));
loss = -d; % Maximize Bhattacharyya distance
loss = dlarray(loss); % Ensure loss is a tracked dlarray scalar
end
% Model gradient function
function [gradients, loss] = modelGradients(dlnet, dlX, N)
Y = forward(dlnet, dlX);
loss = customLoss(Y, N);
gradients = dlgradient(loss, dlnet.Learnables);
end
% Update function
function param = sgdmupdate(param, grad, learnRate)
param = param – learnRate * grad;
end Hello, I am working on customizing the loss function to minimize dimensionality by maximizing the Bhattacharyya distance distance.
But it came up with a error shown as:
Incorrect use of dlarray/dlgradient
The requested value was not tracked. It must be a real dlarray scalar for tracking. Please use dlgradient to track variables in the function called by dlfestival.
% Parameter settings
M = 10; % Dimension of input features
N = 50; % Number of samples per class
numEpochs = 100;
learnRate = 0.01;
% Generate example data
X = rand(2*N, M);
X(1:N, 🙂 = X(1:N, 🙂 + 1; % Data for class A
X(N+1:end, 🙂 = X(N+1:end, 🙂 – 1; % Data for class B
% Define the neural network
layers = [
featureInputLayer(M, ‘Normalization’, ‘none’)
fullyConnectedLayer(10)
reluLayer
fullyConnectedLayer(3)
];
dlnet = dlnetwork(layerGraph(layers));
% Custom training loop
for epoch = 1:numEpochs
dlX = dlarray(X’, ‘CB’); % Transpose input data to match network’s expected format
[gradients, loss] = dlfeval(@modelGradients, dlnet, dlX, N);
dlnet = dlupdate(@sgdmupdate, dlnet, gradients, learnRate);
disp([‘Epoch ‘ num2str(epoch) ‘, Loss: ‘ num2str(extractdata(loss))]);
end
% Testing phase
X_test = rand(N, M); % Assume test data is randomly generated
dlX_test = dlarray(X_test’, ‘CB’); % Transpose input data to match network’s expected format
Y_test = predict(dlnet, dlX_test);
disp(‘Dimensionality reduction results during testing:’);
disp(extractdata(Y_test)’);
% Custom loss function
function loss = customLoss(Y, N)
YA = extractdata(Y(:, 1:N))’;
YB = extractdata(Y(:, N+1:end))’;
muA = mean(YA);
muB = mean(YB);
covA = cov(YA);
covB = cov(YB);
covMean = (covA + covB) / 2;
d = 0.25 * (muA – muB) / covMean * (muA – muB)’ + 0.5 * log(det(covMean) / sqrt(det(covA) * det(covB)));
loss = -d; % Maximize Bhattacharyya distance
loss = dlarray(loss); % Ensure loss is a tracked dlarray scalar
end
% Model gradient function
function [gradients, loss] = modelGradients(dlnet, dlX, N)
Y = forward(dlnet, dlX);
loss = customLoss(Y, N);
gradients = dlgradient(loss, dlnet.Learnables);
end
% Update function
function param = sgdmupdate(param, grad, learnRate)
param = param – learnRate * grad;
end deep learning MATLAB Answers — New Questions
Converting Unix Timestamp to Date Time
Hi,
I’m trying to convert Unix time stamps to date time. So far I have tried:
date_time=(timestamp_array./86400000) + datetime(1970,1,1);
This seems to work find, except that my first measurment was 2123 seconds off. I looked at a few other times and they were 2122 seconds off, 2125 seconds off, etc. I’m not sure what could be causing this discrepancy.
Here is my original time data:
And here is what I am getting after I use my code:
Any insights would be much appreciated!!
(I had to divide my timestamps by 86400000 instead of 86400 becuase all my timestamsps have 3 extra zeros for some reason. Also, all measurements are on the same day if that makes any difference)Hi,
I’m trying to convert Unix time stamps to date time. So far I have tried:
date_time=(timestamp_array./86400000) + datetime(1970,1,1);
This seems to work find, except that my first measurment was 2123 seconds off. I looked at a few other times and they were 2122 seconds off, 2125 seconds off, etc. I’m not sure what could be causing this discrepancy.
Here is my original time data:
And here is what I am getting after I use my code:
Any insights would be much appreciated!!
(I had to divide my timestamps by 86400000 instead of 86400 becuase all my timestamsps have 3 extra zeros for some reason. Also, all measurements are on the same day if that makes any difference) Hi,
I’m trying to convert Unix time stamps to date time. So far I have tried:
date_time=(timestamp_array./86400000) + datetime(1970,1,1);
This seems to work find, except that my first measurment was 2123 seconds off. I looked at a few other times and they were 2122 seconds off, 2125 seconds off, etc. I’m not sure what could be causing this discrepancy.
Here is my original time data:
And here is what I am getting after I use my code:
Any insights would be much appreciated!!
(I had to divide my timestamps by 86400000 instead of 86400 becuase all my timestamsps have 3 extra zeros for some reason. Also, all measurements are on the same day if that makes any difference) datetime, unix, datenum, time series MATLAB Answers — New Questions
Incomplete plot of an integral function
Hi,
I’m having a problem plotting an integal function. Basically, the graph comes out incomplete. Am I doing something wrong or is there a more efficient way to plot the intgral of function (f)? I’ve attached the graph I’m getting and the code I’m using. Your help is greatly appreciated.
syms t X Y;
d=0.5;
f= 121864 *(exp(-2*(((X-(-d*cos(628*t)+7*t)).^2) + ((Y-(d*sin(628*t))).^2))/0.0002)) ;
Z =int(f,t,0,0.4);
fsurf(Z,[-0.1 1.22 -0.61 0.61],’EdgeColor’,’none’);
view([0,90]);
colormap jet;
colorbar;
ax = gca;
ax.FontSize = 24;
xlabel(‘X(mm)’)
ylabel(‘Y(mm)’)
zlabel(‘E=J/mm^2’)Hi,
I’m having a problem plotting an integal function. Basically, the graph comes out incomplete. Am I doing something wrong or is there a more efficient way to plot the intgral of function (f)? I’ve attached the graph I’m getting and the code I’m using. Your help is greatly appreciated.
syms t X Y;
d=0.5;
f= 121864 *(exp(-2*(((X-(-d*cos(628*t)+7*t)).^2) + ((Y-(d*sin(628*t))).^2))/0.0002)) ;
Z =int(f,t,0,0.4);
fsurf(Z,[-0.1 1.22 -0.61 0.61],’EdgeColor’,’none’);
view([0,90]);
colormap jet;
colorbar;
ax = gca;
ax.FontSize = 24;
xlabel(‘X(mm)’)
ylabel(‘Y(mm)’)
zlabel(‘E=J/mm^2’) Hi,
I’m having a problem plotting an integal function. Basically, the graph comes out incomplete. Am I doing something wrong or is there a more efficient way to plot the intgral of function (f)? I’ve attached the graph I’m getting and the code I’m using. Your help is greatly appreciated.
syms t X Y;
d=0.5;
f= 121864 *(exp(-2*(((X-(-d*cos(628*t)+7*t)).^2) + ((Y-(d*sin(628*t))).^2))/0.0002)) ;
Z =int(f,t,0,0.4);
fsurf(Z,[-0.1 1.22 -0.61 0.61],’EdgeColor’,’none’);
view([0,90]);
colormap jet;
colorbar;
ax = gca;
ax.FontSize = 24;
xlabel(‘X(mm)’)
ylabel(‘Y(mm)’)
zlabel(‘E=J/mm^2’) integral, integration, plotting, 3d plots MATLAB Answers — New Questions
Can I create a new serial port on the Arduino Uno to run a Simulink model in real time that also uses a serial port?
I’m attempting to run the example MODBUS RS485 Communication Between Client and Server Using Arduino Board with two Arduino Uno units. These units have only one dedicated serial port on pins 0 and 1. When I go to Monitor and Tune the Client Model, I get an error message for all 6 MODBUS blocks in the model that reads:
Error evaluating ‘InitFcn’ callback of codertarget.arduinobase.internal.arduino_ModbusRS485MasterRead block (mask) ‘arduino_modbus_client/Modbus RS485 Client Read’.
Callback string is ‘codertarget.arduinobase.conflictcheck.validateandregisterBlocks(gcbh);’
Caused by:
The SerialPin_1 ‘1’ being used by ‘arduino_modbus_client/Modbus RS485 Client Read’ is currently in use by ‘Monitor and tune over XCP on Serial’. To resolve the conflict, change the value of SerialPin_1 in ‘arduino_modbus_client/Modbus RS485 Client Read’ to an alternate valid value.
It appears that the only port the Arduino Uno has is in use by the USB interface with my desktop computer. I know that ArduinoIDE has the SoftwareSerial library addon that is supposed to allow you to assign pins to create a separate serial port, but I don’t know if a similar operation is possible in Simulink. Or perhaps I can create the new port in ArduinoIDE for use in the Simulink model. Thank you.I’m attempting to run the example MODBUS RS485 Communication Between Client and Server Using Arduino Board with two Arduino Uno units. These units have only one dedicated serial port on pins 0 and 1. When I go to Monitor and Tune the Client Model, I get an error message for all 6 MODBUS blocks in the model that reads:
Error evaluating ‘InitFcn’ callback of codertarget.arduinobase.internal.arduino_ModbusRS485MasterRead block (mask) ‘arduino_modbus_client/Modbus RS485 Client Read’.
Callback string is ‘codertarget.arduinobase.conflictcheck.validateandregisterBlocks(gcbh);’
Caused by:
The SerialPin_1 ‘1’ being used by ‘arduino_modbus_client/Modbus RS485 Client Read’ is currently in use by ‘Monitor and tune over XCP on Serial’. To resolve the conflict, change the value of SerialPin_1 in ‘arduino_modbus_client/Modbus RS485 Client Read’ to an alternate valid value.
It appears that the only port the Arduino Uno has is in use by the USB interface with my desktop computer. I know that ArduinoIDE has the SoftwareSerial library addon that is supposed to allow you to assign pins to create a separate serial port, but I don’t know if a similar operation is possible in Simulink. Or perhaps I can create the new port in ArduinoIDE for use in the Simulink model. Thank you. I’m attempting to run the example MODBUS RS485 Communication Between Client and Server Using Arduino Board with two Arduino Uno units. These units have only one dedicated serial port on pins 0 and 1. When I go to Monitor and Tune the Client Model, I get an error message for all 6 MODBUS blocks in the model that reads:
Error evaluating ‘InitFcn’ callback of codertarget.arduinobase.internal.arduino_ModbusRS485MasterRead block (mask) ‘arduino_modbus_client/Modbus RS485 Client Read’.
Callback string is ‘codertarget.arduinobase.conflictcheck.validateandregisterBlocks(gcbh);’
Caused by:
The SerialPin_1 ‘1’ being used by ‘arduino_modbus_client/Modbus RS485 Client Read’ is currently in use by ‘Monitor and tune over XCP on Serial’. To resolve the conflict, change the value of SerialPin_1 in ‘arduino_modbus_client/Modbus RS485 Client Read’ to an alternate valid value.
It appears that the only port the Arduino Uno has is in use by the USB interface with my desktop computer. I know that ArduinoIDE has the SoftwareSerial library addon that is supposed to allow you to assign pins to create a separate serial port, but I don’t know if a similar operation is possible in Simulink. Or perhaps I can create the new port in ArduinoIDE for use in the Simulink model. Thank you. arduino, serial, communication MATLAB Answers — New Questions
Automated controls project DC motor controlcre
Automated controls project DC motor control
1..Mathimathical Model of the system
2. Simulink model of the DC Motor(simulink file)
3. Root locus diagram using matlab
4. Intrducing of PID controlel
5. System response before and after adding the PID controller
6. ConclusionAutomated controls project DC motor control
1..Mathimathical Model of the system
2. Simulink model of the DC Motor(simulink file)
3. Root locus diagram using matlab
4. Intrducing of PID controlel
5. System response before and after adding the PID controller
6. Conclusion Automated controls project DC motor control
1..Mathimathical Model of the system
2. Simulink model of the DC Motor(simulink file)
3. Root locus diagram using matlab
4. Intrducing of PID controlel
5. System response before and after adding the PID controller
6. Conclusion create code MATLAB Answers — New Questions
Serial Receive in Desktop Real-Time Kernel Mode
I am trying to get an input from a serial input in Simulink Desktop Real-Time.
To do so I have a "Serial Configuration" block and a "Serial Receive" block which is connected to a "To Workspace" block. (see screenshot below)
I am able to run the model in "Conneceted IO Mode". However, if I change the mode to "Kernel Mode", the model does not work anymore. Simulink states:
Serial Failed Code genreation inofrmation file does not exist.
0 of 1 models built (0 models already up to date)
Build duration: 0h 0m 19.781s
Error(s) encountered while building "Serial_Read"
Is it possible to use serial inputs in "Kernel Mode"? If yes, how can I avoid getting this error?I am trying to get an input from a serial input in Simulink Desktop Real-Time.
To do so I have a "Serial Configuration" block and a "Serial Receive" block which is connected to a "To Workspace" block. (see screenshot below)
I am able to run the model in "Conneceted IO Mode". However, if I change the mode to "Kernel Mode", the model does not work anymore. Simulink states:
Serial Failed Code genreation inofrmation file does not exist.
0 of 1 models built (0 models already up to date)
Build duration: 0h 0m 19.781s
Error(s) encountered while building "Serial_Read"
Is it possible to use serial inputs in "Kernel Mode"? If yes, how can I avoid getting this error? I am trying to get an input from a serial input in Simulink Desktop Real-Time.
To do so I have a "Serial Configuration" block and a "Serial Receive" block which is connected to a "To Workspace" block. (see screenshot below)
I am able to run the model in "Conneceted IO Mode". However, if I change the mode to "Kernel Mode", the model does not work anymore. Simulink states:
Serial Failed Code genreation inofrmation file does not exist.
0 of 1 models built (0 models already up to date)
Build duration: 0h 0m 19.781s
Error(s) encountered while building "Serial_Read"
Is it possible to use serial inputs in "Kernel Mode"? If yes, how can I avoid getting this error? simulink, real-time, kernel mode, serial, serial receive MATLAB Answers — New Questions
writestruct() fails to write empty child element to XML file
I need to write a empty, nested element within an XML file. An XML example of what I’d like to achieve is:
<?xml version="1.0" encoding="UTF-8"?>
<Problem>
<elementA>14</elementA>
<elementB>
<child/>
</elementB>
</Problem>
The nested element in this case is called "child". I expected the following MATLAB code to produce this result:
s.elementA = 14;
s.elementB.child = [];
writestruct(s,’test.xml’,’StructNodeName’,’Problem’)
However, this generates the following XML, whereupon the "child" element is entirely missing:
<?xml version="1.0" encoding="UTF-8"?>
<Problem>
<elementA>14</elementA>
<elementB/>
</Problem>
How can I produce a result with an empty, nested element?I need to write a empty, nested element within an XML file. An XML example of what I’d like to achieve is:
<?xml version="1.0" encoding="UTF-8"?>
<Problem>
<elementA>14</elementA>
<elementB>
<child/>
</elementB>
</Problem>
The nested element in this case is called "child". I expected the following MATLAB code to produce this result:
s.elementA = 14;
s.elementB.child = [];
writestruct(s,’test.xml’,’StructNodeName’,’Problem’)
However, this generates the following XML, whereupon the "child" element is entirely missing:
<?xml version="1.0" encoding="UTF-8"?>
<Problem>
<elementA>14</elementA>
<elementB/>
</Problem>
How can I produce a result with an empty, nested element? I need to write a empty, nested element within an XML file. An XML example of what I’d like to achieve is:
<?xml version="1.0" encoding="UTF-8"?>
<Problem>
<elementA>14</elementA>
<elementB>
<child/>
</elementB>
</Problem>
The nested element in this case is called "child". I expected the following MATLAB code to produce this result:
s.elementA = 14;
s.elementB.child = [];
writestruct(s,’test.xml’,’StructNodeName’,’Problem’)
However, this generates the following XML, whereupon the "child" element is entirely missing:
<?xml version="1.0" encoding="UTF-8"?>
<Problem>
<elementA>14</elementA>
<elementB/>
</Problem>
How can I produce a result with an empty, nested element? writestruct, xml, structures MATLAB Answers — New Questions
How to solve non_linear equation
Post Content Post Content @staff MATLAB Answers — New Questions
How can I color the specific region of the image?
Hi!
I want to change the color of specific region in an image. The background color should be different from the eyes color of the image shown below. Thanks
img = imread(‘C:UsersJunaid KhanDesktopjun.png’);
bn=im2bw(img);
imshow(bn)
bn=bwareaopen(bn,100);
imshow(bn)
[L,n]=bwlabel(bn);
imshow(label2rgb(L));
prop=regionprops(L);
The above is the input image and while I run this code the output is like this.
I want to change the eyes and mouth color and also the background color should not be same.
ThanksHi!
I want to change the color of specific region in an image. The background color should be different from the eyes color of the image shown below. Thanks
img = imread(‘C:UsersJunaid KhanDesktopjun.png’);
bn=im2bw(img);
imshow(bn)
bn=bwareaopen(bn,100);
imshow(bn)
[L,n]=bwlabel(bn);
imshow(label2rgb(L));
prop=regionprops(L);
The above is the input image and while I run this code the output is like this.
I want to change the eyes and mouth color and also the background color should not be same.
Thanks Hi!
I want to change the color of specific region in an image. The background color should be different from the eyes color of the image shown below. Thanks
img = imread(‘C:UsersJunaid KhanDesktopjun.png’);
bn=im2bw(img);
imshow(bn)
bn=bwareaopen(bn,100);
imshow(bn)
[L,n]=bwlabel(bn);
imshow(label2rgb(L));
prop=regionprops(L);
The above is the input image and while I run this code the output is like this.
I want to change the eyes and mouth color and also the background color should not be same.
Thanks image processing MATLAB Answers — New Questions
PID control action for AC reference of variable amplitude and frequency.
i have seen example of controlling output dc voltage of DC to DC buck converter using PID controller. I want to implement DC to AC converter. I tried using PID controller. Since i am comparing output AC signal(continuously varying) with reference sinusoidal signal, PID controller is not providing expected output. In case of DC to DC, both reference signal was constant. In my case, it is continuously varying sine wave. Can anyone suggest any way to get accurate DC to AC conversion? i changed kp and ki parameters to get needed response. it is working well. but, when i change frequency of input reference signal, output signal amplitude drops and again i have to change PID parameters.
P.S. when i change frequency of input reference signal, again i have to change PID gain parameters. Can PID controller work with continuously varying reference signal(in terms of amplitude and frequency both) ?i have seen example of controlling output dc voltage of DC to DC buck converter using PID controller. I want to implement DC to AC converter. I tried using PID controller. Since i am comparing output AC signal(continuously varying) with reference sinusoidal signal, PID controller is not providing expected output. In case of DC to DC, both reference signal was constant. In my case, it is continuously varying sine wave. Can anyone suggest any way to get accurate DC to AC conversion? i changed kp and ki parameters to get needed response. it is working well. but, when i change frequency of input reference signal, output signal amplitude drops and again i have to change PID parameters.
P.S. when i change frequency of input reference signal, again i have to change PID gain parameters. Can PID controller work with continuously varying reference signal(in terms of amplitude and frequency both) ? i have seen example of controlling output dc voltage of DC to DC buck converter using PID controller. I want to implement DC to AC converter. I tried using PID controller. Since i am comparing output AC signal(continuously varying) with reference sinusoidal signal, PID controller is not providing expected output. In case of DC to DC, both reference signal was constant. In my case, it is continuously varying sine wave. Can anyone suggest any way to get accurate DC to AC conversion? i changed kp and ki parameters to get needed response. it is working well. but, when i change frequency of input reference signal, output signal amplitude drops and again i have to change PID parameters.
P.S. when i change frequency of input reference signal, again i have to change PID gain parameters. Can PID controller work with continuously varying reference signal(in terms of amplitude and frequency both) ? simulink MATLAB Answers — New Questions
Pseudo-terminal will not be allocated because stdin is not a terminal.
When trying to ssh to linux device form matlab scirpts, i get these messages as in screenshot, any thoughts why this can happen and how can we get terminal?When trying to ssh to linux device form matlab scirpts, i get these messages as in screenshot, any thoughts why this can happen and how can we get terminal? When trying to ssh to linux device form matlab scirpts, i get these messages as in screenshot, any thoughts why this can happen and how can we get terminal? matlab MATLAB Answers — New Questions