Category: Matlab
Category Archives: Matlab
Cylinder with gyroid infill
Hello,
I have following matlab code
% Clear all previous commands
clear all
close all
clc
% Variables you can change
SizeL = 20; %average length of RVE
Def = 40; %definition
% Variables you shouldn´t change
SFact = (SizeL/2)/pi; %size factor of RVE
A = SFact*pi; %lowest and max coordinates of meshgrid
D = A/Def; %definition factor
% Generation of gyroids
[X,Y,Z] = meshgrid(-A:D:A); %creates mesh grid
% Gyroid equation
OBJ = cos(X/SFact).* sin(Y/SFact) + cos(Y/SFact).* sin(Z/SFact)…
+ cos(Z/SFact).* sin(X/SFact)+(0);
T = 0.5;
OBJ = (OBJ-T).*(OBJ+T);
% Isosurface and isocap
[F1,V1] = isosurface(X,Y,Z,OBJ,0);
[F2,V2] = isocaps(X,Y,Z,OBJ,0,’below’);
%Combines isosurface and isocaps into one
F3 = [F1;F2+length(V1(:,1))];
V3 = [V1;V2];
% Visualization
P = patch(‘Vertices’,V3,’Faces’,F3,’FaceColor’, …
‘red’,’EdgeColor’,’none’);
view(3)
camlight
% STL export of independet files per gyroid.
% Change current file path with desired file path.
stlwrite([‘C:…filepath…G1-T05’ num2str(1) ‘.stl’],F3,V3);
It generates cubical unit cell with gyroid infill. I would need to change it to produce the cylindrical unit cell with height H and radius R with the same infill. I am failing to change the code. Can you help me?
Thank youHello,
I have following matlab code
% Clear all previous commands
clear all
close all
clc
% Variables you can change
SizeL = 20; %average length of RVE
Def = 40; %definition
% Variables you shouldn´t change
SFact = (SizeL/2)/pi; %size factor of RVE
A = SFact*pi; %lowest and max coordinates of meshgrid
D = A/Def; %definition factor
% Generation of gyroids
[X,Y,Z] = meshgrid(-A:D:A); %creates mesh grid
% Gyroid equation
OBJ = cos(X/SFact).* sin(Y/SFact) + cos(Y/SFact).* sin(Z/SFact)…
+ cos(Z/SFact).* sin(X/SFact)+(0);
T = 0.5;
OBJ = (OBJ-T).*(OBJ+T);
% Isosurface and isocap
[F1,V1] = isosurface(X,Y,Z,OBJ,0);
[F2,V2] = isocaps(X,Y,Z,OBJ,0,’below’);
%Combines isosurface and isocaps into one
F3 = [F1;F2+length(V1(:,1))];
V3 = [V1;V2];
% Visualization
P = patch(‘Vertices’,V3,’Faces’,F3,’FaceColor’, …
‘red’,’EdgeColor’,’none’);
view(3)
camlight
% STL export of independet files per gyroid.
% Change current file path with desired file path.
stlwrite([‘C:…filepath…G1-T05’ num2str(1) ‘.stl’],F3,V3);
It generates cubical unit cell with gyroid infill. I would need to change it to produce the cylindrical unit cell with height H and radius R with the same infill. I am failing to change the code. Can you help me?
Thank you Hello,
I have following matlab code
% Clear all previous commands
clear all
close all
clc
% Variables you can change
SizeL = 20; %average length of RVE
Def = 40; %definition
% Variables you shouldn´t change
SFact = (SizeL/2)/pi; %size factor of RVE
A = SFact*pi; %lowest and max coordinates of meshgrid
D = A/Def; %definition factor
% Generation of gyroids
[X,Y,Z] = meshgrid(-A:D:A); %creates mesh grid
% Gyroid equation
OBJ = cos(X/SFact).* sin(Y/SFact) + cos(Y/SFact).* sin(Z/SFact)…
+ cos(Z/SFact).* sin(X/SFact)+(0);
T = 0.5;
OBJ = (OBJ-T).*(OBJ+T);
% Isosurface and isocap
[F1,V1] = isosurface(X,Y,Z,OBJ,0);
[F2,V2] = isocaps(X,Y,Z,OBJ,0,’below’);
%Combines isosurface and isocaps into one
F3 = [F1;F2+length(V1(:,1))];
V3 = [V1;V2];
% Visualization
P = patch(‘Vertices’,V3,’Faces’,F3,’FaceColor’, …
‘red’,’EdgeColor’,’none’);
view(3)
camlight
% STL export of independet files per gyroid.
% Change current file path with desired file path.
stlwrite([‘C:…filepath…G1-T05’ num2str(1) ‘.stl’],F3,V3);
It generates cubical unit cell with gyroid infill. I would need to change it to produce the cylindrical unit cell with height H and radius R with the same infill. I am failing to change the code. Can you help me?
Thank you gyroid, .stl MATLAB Answers — New Questions
Execute commands from an external .exe application
How can I issue commands from Matlab to an external .exe application?
I need to open an exe application and perform a repetitive operation a large number of times, so I need to automate this process.How can I issue commands from Matlab to an external .exe application?
I need to open an exe application and perform a repetitive operation a large number of times, so I need to automate this process. How can I issue commands from Matlab to an external .exe application?
I need to open an exe application and perform a repetitive operation a large number of times, so I need to automate this process. externalcommand, exeprogram, automate MATLAB Answers — New Questions
Want to programmatically get the Maltlab status of (ready, busy), etc., in the bottom left corner of the window. What procedure will be used?
It’s framed in red in the bottom left corner of the window.It’s framed in red in the bottom left corner of the window. It’s framed in red in the bottom left corner of the window. programming MATLAB Answers — New Questions
How to find relative loading factors on the primary principal component?
I have a set of color images sized 600*600.I extracted 16 color channels from each image and changed each channel into column matrix sized 360000*1 and concatenated each 16 channels to form 360000*16 matrix.Now I want to implement PCA on it to identify the most discriminative channel.Implemented code is given below:
Xi=[Rcol,Gcol,Bcol,Hcol,Scol,Vcol,Ycol,Icol,Qcol,L1col,acol,bcol,M1col,M21col,M3col,M61col];
avg=mean(Xi);
sd=std(Xi,0,1);
Xnorm=bsxfun(@minus,Xi,avg);
Xnorm = bsxfun(@rdivide,Xnorm,sd);
Xi1=cov(Xnorm);
[V, D]=eig(Xi1);
In implementing paper they say to analyze the relative loading factor of different color channels on the primary principal component.So can you tell me how to calculate loading factor on primary principal component using matlab?I have a set of color images sized 600*600.I extracted 16 color channels from each image and changed each channel into column matrix sized 360000*1 and concatenated each 16 channels to form 360000*16 matrix.Now I want to implement PCA on it to identify the most discriminative channel.Implemented code is given below:
Xi=[Rcol,Gcol,Bcol,Hcol,Scol,Vcol,Ycol,Icol,Qcol,L1col,acol,bcol,M1col,M21col,M3col,M61col];
avg=mean(Xi);
sd=std(Xi,0,1);
Xnorm=bsxfun(@minus,Xi,avg);
Xnorm = bsxfun(@rdivide,Xnorm,sd);
Xi1=cov(Xnorm);
[V, D]=eig(Xi1);
In implementing paper they say to analyze the relative loading factor of different color channels on the primary principal component.So can you tell me how to calculate loading factor on primary principal component using matlab? I have a set of color images sized 600*600.I extracted 16 color channels from each image and changed each channel into column matrix sized 360000*1 and concatenated each 16 channels to form 360000*16 matrix.Now I want to implement PCA on it to identify the most discriminative channel.Implemented code is given below:
Xi=[Rcol,Gcol,Bcol,Hcol,Scol,Vcol,Ycol,Icol,Qcol,L1col,acol,bcol,M1col,M21col,M3col,M61col];
avg=mean(Xi);
sd=std(Xi,0,1);
Xnorm=bsxfun(@minus,Xi,avg);
Xnorm = bsxfun(@rdivide,Xnorm,sd);
Xi1=cov(Xnorm);
[V, D]=eig(Xi1);
In implementing paper they say to analyze the relative loading factor of different color channels on the primary principal component.So can you tell me how to calculate loading factor on primary principal component using matlab? image processing, pca, loading factor MATLAB Answers — New Questions
Extracting data from struct as matrix
Hi,
I have the following struct:
S(1).a = 1:5;
S(2).a = 11:10;
S(3).a = 21:27;
Is there a way to vertically concatenate them without looping? I cannot do vertcat(S.a) because data is of different size.
I want output like this [1:5; 11:10; 21:27]
Thank youHi,
I have the following struct:
S(1).a = 1:5;
S(2).a = 11:10;
S(3).a = 21:27;
Is there a way to vertically concatenate them without looping? I cannot do vertcat(S.a) because data is of different size.
I want output like this [1:5; 11:10; 21:27]
Thank you Hi,
I have the following struct:
S(1).a = 1:5;
S(2).a = 11:10;
S(3).a = 21:27;
Is there a way to vertically concatenate them without looping? I cannot do vertcat(S.a) because data is of different size.
I want output like this [1:5; 11:10; 21:27]
Thank you #structure MATLAB Answers — New Questions
How to call a function containing large dataset of inputs and target attribute in matlab function block
function y=RefGen(u1,u2)
[u1,u2,yd]=dsdata();
x=[u1 u2];
Here u1 and u2 are inputs and y is the output,
dsdata() is the function to be called in the matlab function block
u1 and u2 will assign the input vectors containing 100 samples each and yd will assign the target attribute
x is the input matrix containing u1 and u2 inputsfunction y=RefGen(u1,u2)
[u1,u2,yd]=dsdata();
x=[u1 u2];
Here u1 and u2 are inputs and y is the output,
dsdata() is the function to be called in the matlab function block
u1 and u2 will assign the input vectors containing 100 samples each and yd will assign the target attribute
x is the input matrix containing u1 and u2 inputs function y=RefGen(u1,u2)
[u1,u2,yd]=dsdata();
x=[u1 u2];
Here u1 and u2 are inputs and y is the output,
dsdata() is the function to be called in the matlab function block
u1 and u2 will assign the input vectors containing 100 samples each and yd will assign the target attribute
x is the input matrix containing u1 and u2 inputs solar pv mppt, matlab, simulink, ann, neural network simulink in matlab MATLAB Answers — New Questions
close autosar update report
How to close autosar update report with script e.g. after running updateModel(ar, ‘abc’)How to close autosar update report with script e.g. after running updateModel(ar, ‘abc’) How to close autosar update report with script e.g. after running updateModel(ar, ‘abc’) autosar update MATLAB Answers — New Questions
Extracting data from struct as array
Hi, I have a following structure:
S(1).a = 1:10;
S(2).a = 11:20;
S(3).a = 21:30;
I want the output in the following format:
y = [1:10; 11:20; 21:30];
Using [S(1:3).a] concatenates it in a single direction. Is there a better way (other than for loop) to extract the data in the requisite format?
Thank you,
RashiHi, I have a following structure:
S(1).a = 1:10;
S(2).a = 11:20;
S(3).a = 21:30;
I want the output in the following format:
y = [1:10; 11:20; 21:30];
Using [S(1:3).a] concatenates it in a single direction. Is there a better way (other than for loop) to extract the data in the requisite format?
Thank you,
Rashi Hi, I have a following structure:
S(1).a = 1:10;
S(2).a = 11:20;
S(3).a = 21:30;
I want the output in the following format:
y = [1:10; 11:20; 21:30];
Using [S(1:3).a] concatenates it in a single direction. Is there a better way (other than for loop) to extract the data in the requisite format?
Thank you,
Rashi structures, data output, array MATLAB Answers — New Questions
How to plot vectors of zonally averaged meridional-vertical wind circulation in a latitude-pressure cross-section in MATLAB
Dear all,
I have 3D matrices (longitude*latitude*plev) of U, V and W-components of wind. Since I want to plot latitude-pressure vertical cross section, I took average along the first dimension (i.e, longitude) for V and W-components of wind. Also, initially I had the plev data with 12 pressure levels. But, I created 91 interpolated pressure levels using ‘meshgrid’ command and interpolated the V and W-components of wind data at each pressure levels using ‘griddata’ command, like in the following:
[X_LAT,Y_PLEV]=meshgrid(latitude,min(plev):10:max(plev));
V=griddata(latitude,plev,Vwind’,X_LAT,Y_PLEV);
%same as for W wind
For your convenience, I attached the latitude, plev, V, and W matrices. But, when I tried to plot the wind vectors along latitude-pressure vertical cross-section using ‘quiversc’ function, I am getting absurd vectors (see the figure attached). But, previously, with the same ‘quiversc’ function, I got the correct wind vectors when I used U and V-components of wind at x-y plane for a particular pressure level. So, I think, there is nothing wrong with the function. Maybe the code should be different this time as I am plotting latitude-pressure vertical cross section. My code for plotting is as follows:
contourf(X_LAT,Y_PLEV,W,40,’linecolor’,’none’) ;
set(gca,’YDir’,’reverse’);
set(gca,’yscale’,’log’)
hold on
q1=quiversc(X_LAT,Y_PLEV,V,W,’density’,10,’MaxHeadSize’,5,’AutoScale’,’on’,’color’,’k’,’LineWidth’,1);
colormap(jet(50))
caxis([-2 2])
xlim([-7 1])
ylim([100 1000])
box on
set(gca,’YTick’,(100:100:1000),’YTickLabel’,{‘100’ ‘200’ ‘300’ ‘400’ ‘500’ ‘600’ ‘700’ ‘800’ ‘900’ ‘1000’},’FontName’, ‘Arial’,’FontSize’,14,’FontWeight’,’bold’,’LineWidth’,1)
Now, it is important to note that I multiplied W by 100 for scaling as per the V wind. Since, the vertical cross-section is along the latitudes, so I think quiversc should work with V and W to get the meridional-vertical wind circulation vector. Right? Or, do I have to do something additional to get the desired plot. For your reference, I attached a sample figure from Zhu et al. (2022). Can anyone please help me to solve this issue? That will be very helpful for me. Thank you for your time and consideration.Dear all,
I have 3D matrices (longitude*latitude*plev) of U, V and W-components of wind. Since I want to plot latitude-pressure vertical cross section, I took average along the first dimension (i.e, longitude) for V and W-components of wind. Also, initially I had the plev data with 12 pressure levels. But, I created 91 interpolated pressure levels using ‘meshgrid’ command and interpolated the V and W-components of wind data at each pressure levels using ‘griddata’ command, like in the following:
[X_LAT,Y_PLEV]=meshgrid(latitude,min(plev):10:max(plev));
V=griddata(latitude,plev,Vwind’,X_LAT,Y_PLEV);
%same as for W wind
For your convenience, I attached the latitude, plev, V, and W matrices. But, when I tried to plot the wind vectors along latitude-pressure vertical cross-section using ‘quiversc’ function, I am getting absurd vectors (see the figure attached). But, previously, with the same ‘quiversc’ function, I got the correct wind vectors when I used U and V-components of wind at x-y plane for a particular pressure level. So, I think, there is nothing wrong with the function. Maybe the code should be different this time as I am plotting latitude-pressure vertical cross section. My code for plotting is as follows:
contourf(X_LAT,Y_PLEV,W,40,’linecolor’,’none’) ;
set(gca,’YDir’,’reverse’);
set(gca,’yscale’,’log’)
hold on
q1=quiversc(X_LAT,Y_PLEV,V,W,’density’,10,’MaxHeadSize’,5,’AutoScale’,’on’,’color’,’k’,’LineWidth’,1);
colormap(jet(50))
caxis([-2 2])
xlim([-7 1])
ylim([100 1000])
box on
set(gca,’YTick’,(100:100:1000),’YTickLabel’,{‘100’ ‘200’ ‘300’ ‘400’ ‘500’ ‘600’ ‘700’ ‘800’ ‘900’ ‘1000’},’FontName’, ‘Arial’,’FontSize’,14,’FontWeight’,’bold’,’LineWidth’,1)
Now, it is important to note that I multiplied W by 100 for scaling as per the V wind. Since, the vertical cross-section is along the latitudes, so I think quiversc should work with V and W to get the meridional-vertical wind circulation vector. Right? Or, do I have to do something additional to get the desired plot. For your reference, I attached a sample figure from Zhu et al. (2022). Can anyone please help me to solve this issue? That will be very helpful for me. Thank you for your time and consideration. Dear all,
I have 3D matrices (longitude*latitude*plev) of U, V and W-components of wind. Since I want to plot latitude-pressure vertical cross section, I took average along the first dimension (i.e, longitude) for V and W-components of wind. Also, initially I had the plev data with 12 pressure levels. But, I created 91 interpolated pressure levels using ‘meshgrid’ command and interpolated the V and W-components of wind data at each pressure levels using ‘griddata’ command, like in the following:
[X_LAT,Y_PLEV]=meshgrid(latitude,min(plev):10:max(plev));
V=griddata(latitude,plev,Vwind’,X_LAT,Y_PLEV);
%same as for W wind
For your convenience, I attached the latitude, plev, V, and W matrices. But, when I tried to plot the wind vectors along latitude-pressure vertical cross-section using ‘quiversc’ function, I am getting absurd vectors (see the figure attached). But, previously, with the same ‘quiversc’ function, I got the correct wind vectors when I used U and V-components of wind at x-y plane for a particular pressure level. So, I think, there is nothing wrong with the function. Maybe the code should be different this time as I am plotting latitude-pressure vertical cross section. My code for plotting is as follows:
contourf(X_LAT,Y_PLEV,W,40,’linecolor’,’none’) ;
set(gca,’YDir’,’reverse’);
set(gca,’yscale’,’log’)
hold on
q1=quiversc(X_LAT,Y_PLEV,V,W,’density’,10,’MaxHeadSize’,5,’AutoScale’,’on’,’color’,’k’,’LineWidth’,1);
colormap(jet(50))
caxis([-2 2])
xlim([-7 1])
ylim([100 1000])
box on
set(gca,’YTick’,(100:100:1000),’YTickLabel’,{‘100’ ‘200’ ‘300’ ‘400’ ‘500’ ‘600’ ‘700’ ‘800’ ‘900’ ‘1000’},’FontName’, ‘Arial’,’FontSize’,14,’FontWeight’,’bold’,’LineWidth’,1)
Now, it is important to note that I multiplied W by 100 for scaling as per the V wind. Since, the vertical cross-section is along the latitudes, so I think quiversc should work with V and W to get the meridional-vertical wind circulation vector. Right? Or, do I have to do something additional to get the desired plot. For your reference, I attached a sample figure from Zhu et al. (2022). Can anyone please help me to solve this issue? That will be very helpful for me. Thank you for your time and consideration. matlab, vector MATLAB Answers — New Questions
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