Category: Matlab
Category Archives: Matlab
Why are graphic positions not observable properties?
Back story: I am trying to port dialog boxes based on uicontrols to their uifigure equivalents: uilabel, uibutton, etc. The old system allowed you to size items based on the text contained within using the Extent property. For example, one could add a button with the String ‘Apply’, adjust the position to accomodate that text, and then size the figure as needed. Newer components lack an Extent property, and the closest I can come to that feature is stacking things in a uigridlayout using ‘fit’ for the row height and column width. However, there is noticeable lag, around a second or so, between when the component is created and grid sizing. The attached function illustrates this with a separate plot showing how long it takes for a uilable’s width/height to change from its default value.
I thought one would be able to add a listener to the grid or component contained within to see when sizing is complete. However, the Position property is not an observable property for the grid layout or a uilable inside. Is there some reason for that? The lag is bad enough, but at least I could keep the figure hidden until all resizing is complete. Right now I have to guess as to how long this might take, put in a manual delay, and then hope all layout grids are done changing before sizing the figure based on what is inside.
FWIW I am using the latest update of R2024b with the desktop beta on a Mac.Back story: I am trying to port dialog boxes based on uicontrols to their uifigure equivalents: uilabel, uibutton, etc. The old system allowed you to size items based on the text contained within using the Extent property. For example, one could add a button with the String ‘Apply’, adjust the position to accomodate that text, and then size the figure as needed. Newer components lack an Extent property, and the closest I can come to that feature is stacking things in a uigridlayout using ‘fit’ for the row height and column width. However, there is noticeable lag, around a second or so, between when the component is created and grid sizing. The attached function illustrates this with a separate plot showing how long it takes for a uilable’s width/height to change from its default value.
I thought one would be able to add a listener to the grid or component contained within to see when sizing is complete. However, the Position property is not an observable property for the grid layout or a uilable inside. Is there some reason for that? The lag is bad enough, but at least I could keep the figure hidden until all resizing is complete. Right now I have to guess as to how long this might take, put in a manual delay, and then hope all layout grids are done changing before sizing the figure based on what is inside.
FWIW I am using the latest update of R2024b with the desktop beta on a Mac. Back story: I am trying to port dialog boxes based on uicontrols to their uifigure equivalents: uilabel, uibutton, etc. The old system allowed you to size items based on the text contained within using the Extent property. For example, one could add a button with the String ‘Apply’, adjust the position to accomodate that text, and then size the figure as needed. Newer components lack an Extent property, and the closest I can come to that feature is stacking things in a uigridlayout using ‘fit’ for the row height and column width. However, there is noticeable lag, around a second or so, between when the component is created and grid sizing. The attached function illustrates this with a separate plot showing how long it takes for a uilable’s width/height to change from its default value.
I thought one would be able to add a listener to the grid or component contained within to see when sizing is complete. However, the Position property is not an observable property for the grid layout or a uilable inside. Is there some reason for that? The lag is bad enough, but at least I could keep the figure hidden until all resizing is complete. Right now I have to guess as to how long this might take, put in a manual delay, and then hope all layout grids are done changing before sizing the figure based on what is inside.
FWIW I am using the latest update of R2024b with the desktop beta on a Mac. graphics, slow, listener MATLAB Answers — New Questions
How can i remove singular Jacobin error from this code?
william()
function william
clc
clear all format long
w=1; %wlmsn
Ha=0.1;
Re=0.4;
angle_degrees=0.1; %omega N,a,Ha,Re,angle_degrees,E,Pr
E=0.1; %Ec
Pr=0.2; %0.01
phi1=0.001;%0.02,0.03
phi2=0.001;%0.03,0.2
rof=997.1;
ro1=8933;
ro2=3970;
rocpf=4179;
rocp1= 385;
rocp2= 765;
kf=0.613;
k1=401;
k2=40
sigmaf=0.05;
sigma1=5.96*10^7;
sigma2=3.69*10^7;
A1=(phi2*rocp2)/rocpf+ (1-phi2)*((1-phi1)+(rocp1*phi1)/rocpf);
A2=((1-phi2)*((1-phi1)+(ro1*phi1)/rof)+(ro2*phi2)/rof);
A= ((sigma1*(1-2*(phi1)) + 2*sigmaf*(1-phi1))/(sigma1*(1-phi1) + 2*sigmaf*(1+phi1))); %sigmaf
A3=((sigma2*(1+2*(phi2))+2*(1-phi2)*A)/(sigma2*(1-phi2)+(2+phi2)*A))*A;
%A3=((sigma2+2*(1-phi2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1))+2*phi2*sigma2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1)))/(sigma2+2*(1+phi2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1))-phi2*sigma2);
A4=((1-phi1)^-2.5)*((1-phi2)^-2.5); %meuf
A5=(((2 * (1 + phi1) * (2 * kf – 2 * phi2 * (k2 – kf) + k2)) / (2 * kf + phi2 * (k2 – kf) + k2) + ((1 – 2 * phi1) * k1) / kf) / (2 – phi1)) * ((2 * kf – 2 * phi2 * (k2 – kf) + k2) / (2 * kf + phi2 * (k2 – kf) + k2)) + ((1 + phi1) * k1) / kf;
infinity=1;
solinit = bvpinit(linspace(0,infinity,20),zeros(5,1));
options=bvpset(‘Stats’,’on’,’RelTol’,1e-6);
lines={‘k’,’r’,’g’,’m’,’k–‘,’r–‘,’g–‘,’b–‘,’y’,’m’,’k’,’b’};
Ha=0.1;
sol1 = bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.3;
sol2 =bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.5;
sol3 =bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.7;
sol4= bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
figure(1);
plot(sol1.x,sol1.y(1,:),lines{1},sol2.x,sol2.y(1,:),lines{2},sol3.x,sol3.y(1,:),lines{3},sol4.x,sol4.y(1,:),lines{4},’LineWidth’,3,’MarkerSize’,16,’linestyle’,’-‘);
xlabel(‘zeta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
ylabel(‘eta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
grid on
hold on
figure(2);
plot(sol1.x,sol1.y(4,:),lines{1},sol2.x,sol2.y(4,:),lines{2},sol3.x,sol3.y(4,:),lines{3},sol4.x,sol4.y(4,:),lines{4},’LineWidth’,3,’MarkerSize’,16,’linestyle’,’-‘);
xlabel(‘zeta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
ylabel(‘kappa’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
grid on
hold on
y1 = sol1.y;
y2 = sol2.y;
function dydx = williamode(x,y,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2)
dydx =zeros(5,1);
dydx = [y(2)
y(3)
%-(sqrt((2*y(1)*angle_degrees)^2 + y(2)^2) / (sqrt((2*y(1)*angle_degrees)^2 + y(2)^2) + w * (2 * y(2)^2 + 4 * y(1)^2 * angle_degrees^2))) * (2 * angle_degrees * Re * A2 * (1 – phi1)^2.5 * (1 – phi2)^2.5 * y(1) * y(2)+(4-A3*(1-phi1)^2.5*(1-phi2)^2.5*(Ha)^2)*y(2)*angle_degrees^2+(w*(sqrt(2*y(1)*angle_degrees)^2+y(2)^2)*((16*y(1)^3*angle_degrees^4*+8*y(1)*y(2)^2*angle_degrees^2+2*y(2)^2*y(3)+4*y(1)^2*y(3)*angle_degrees^2)/(4*y(1)*y(2)*angle_degrees^2+y(2)*y(3))+(1/((2*y(1)*angle_degrees)^2*+y(2)^2))*(80*y(1)^2*y(2)*angle_degrees^4+32*y(1)*y(2)*y(3)*angle_degrees^2+8*y(2)^3*angle_degrees^2+4*y(2)*y(3)^2)));
-(sqrt((2*y(1)*angle_degrees)^2+y(2)^2)/((sqrt((2*y(1)*angle_degrees)^2+y(2)^2))+w*(2*y(2)^2+4*y(1)^2*angle_degrees^2)))*(2*angle_degrees*Re*A2*(1-phi1)^2.5*(1-phi2)^2.5*y(1)*y(2)+(4-A3*(1-phi1)^2.5*(1-phi2)^2.5*(Ha)^2)*y(2)*angle_degrees^2+((w*(sqrt(2*y(1)*angle_degrees)^2+y(2)^2))*((16*y(1)^3*angle_degrees^4*+8*y(1)*y(2)^2*angle_degrees^2+2*y(2)^2*y(3)+4*y(1)^2*y(3)*angle_degrees^2)/(4*y(1)*y(2)*angle_degrees^2+y(2)*y(3)))+((1/((2*y(1)*angle_degrees)^2*+y(2)^2))*(80*y(1)^2*y(2)*angle_degrees^4+32*y(1)*y(2)*y(3)*angle_degrees^2+8*y(2)^3*angle_degrees^2+4*y(2)*y(3)^2))))
%-(sqrt((2 * y(1) * angle_degrees)^2 + y(2)^2) /(sqrt((2 * y(1) * angle_degrees)^2 + y(2)^2) + w * (2 * y(2)^2 + 4 * y(1)^2 * angle_degrees^2)))*(2*angle_degrees *Re*A2*(1 – phi1)^2.5*(1 – phi2)^2.5 * y(1) * y(2) +(4 – A3 * (1 – phi1)^2.5 * (1 – phi2)^2.5 * (Ha)^2) * y(2) * angle_degrees^2 +((w * (sqrt(2 * y(1) * angle_degrees)^2 + y(2)^2)) *((16 * y(1)^3 * angle_degrees^4 + 8 * y(1) * y(2)^2 * angle_degrees^2 + 2 * y(2)^2 * y(3) +4 * y(1)^2 * y(3) * angle_degrees^2) /(4 * y(1) * y(2) * angle_degrees^2 + y(2) * y(3)) +((1 / ((2 * y(1) * angle_degrees)^2 + y(2)^2)) *(80 * y(1)^2 * y(2) * angle_degrees^4 + 32 * y(1) * y(2) * y(3) * angle_degrees^2+8 * y(2)^3 * angle_degrees^2 + 4 * y(2) * y(3)^2)));
y(5)
(-1/A5)*((E*Pr*A1)/(1-phi1)^2.5*(1-phi2)^2.5)*((4*y(1)^2*angle_degrees^2+y(2)^2)+w*((4*y(1)^2*angle_degrees^2+y(2)^2)^3/2))]
end
function res = williambc(ya,yb,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,~,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2)
res =[ya(1)-1;
ya(2);
ya(5);
yb(1);
yb(4)-1;];
hold on
end
grid on
endwilliam()
function william
clc
clear all format long
w=1; %wlmsn
Ha=0.1;
Re=0.4;
angle_degrees=0.1; %omega N,a,Ha,Re,angle_degrees,E,Pr
E=0.1; %Ec
Pr=0.2; %0.01
phi1=0.001;%0.02,0.03
phi2=0.001;%0.03,0.2
rof=997.1;
ro1=8933;
ro2=3970;
rocpf=4179;
rocp1= 385;
rocp2= 765;
kf=0.613;
k1=401;
k2=40
sigmaf=0.05;
sigma1=5.96*10^7;
sigma2=3.69*10^7;
A1=(phi2*rocp2)/rocpf+ (1-phi2)*((1-phi1)+(rocp1*phi1)/rocpf);
A2=((1-phi2)*((1-phi1)+(ro1*phi1)/rof)+(ro2*phi2)/rof);
A= ((sigma1*(1-2*(phi1)) + 2*sigmaf*(1-phi1))/(sigma1*(1-phi1) + 2*sigmaf*(1+phi1))); %sigmaf
A3=((sigma2*(1+2*(phi2))+2*(1-phi2)*A)/(sigma2*(1-phi2)+(2+phi2)*A))*A;
%A3=((sigma2+2*(1-phi2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1))+2*phi2*sigma2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1)))/(sigma2+2*(1+phi2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1))-phi2*sigma2);
A4=((1-phi1)^-2.5)*((1-phi2)^-2.5); %meuf
A5=(((2 * (1 + phi1) * (2 * kf – 2 * phi2 * (k2 – kf) + k2)) / (2 * kf + phi2 * (k2 – kf) + k2) + ((1 – 2 * phi1) * k1) / kf) / (2 – phi1)) * ((2 * kf – 2 * phi2 * (k2 – kf) + k2) / (2 * kf + phi2 * (k2 – kf) + k2)) + ((1 + phi1) * k1) / kf;
infinity=1;
solinit = bvpinit(linspace(0,infinity,20),zeros(5,1));
options=bvpset(‘Stats’,’on’,’RelTol’,1e-6);
lines={‘k’,’r’,’g’,’m’,’k–‘,’r–‘,’g–‘,’b–‘,’y’,’m’,’k’,’b’};
Ha=0.1;
sol1 = bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.3;
sol2 =bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.5;
sol3 =bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.7;
sol4= bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
figure(1);
plot(sol1.x,sol1.y(1,:),lines{1},sol2.x,sol2.y(1,:),lines{2},sol3.x,sol3.y(1,:),lines{3},sol4.x,sol4.y(1,:),lines{4},’LineWidth’,3,’MarkerSize’,16,’linestyle’,’-‘);
xlabel(‘zeta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
ylabel(‘eta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
grid on
hold on
figure(2);
plot(sol1.x,sol1.y(4,:),lines{1},sol2.x,sol2.y(4,:),lines{2},sol3.x,sol3.y(4,:),lines{3},sol4.x,sol4.y(4,:),lines{4},’LineWidth’,3,’MarkerSize’,16,’linestyle’,’-‘);
xlabel(‘zeta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
ylabel(‘kappa’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
grid on
hold on
y1 = sol1.y;
y2 = sol2.y;
function dydx = williamode(x,y,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2)
dydx =zeros(5,1);
dydx = [y(2)
y(3)
%-(sqrt((2*y(1)*angle_degrees)^2 + y(2)^2) / (sqrt((2*y(1)*angle_degrees)^2 + y(2)^2) + w * (2 * y(2)^2 + 4 * y(1)^2 * angle_degrees^2))) * (2 * angle_degrees * Re * A2 * (1 – phi1)^2.5 * (1 – phi2)^2.5 * y(1) * y(2)+(4-A3*(1-phi1)^2.5*(1-phi2)^2.5*(Ha)^2)*y(2)*angle_degrees^2+(w*(sqrt(2*y(1)*angle_degrees)^2+y(2)^2)*((16*y(1)^3*angle_degrees^4*+8*y(1)*y(2)^2*angle_degrees^2+2*y(2)^2*y(3)+4*y(1)^2*y(3)*angle_degrees^2)/(4*y(1)*y(2)*angle_degrees^2+y(2)*y(3))+(1/((2*y(1)*angle_degrees)^2*+y(2)^2))*(80*y(1)^2*y(2)*angle_degrees^4+32*y(1)*y(2)*y(3)*angle_degrees^2+8*y(2)^3*angle_degrees^2+4*y(2)*y(3)^2)));
-(sqrt((2*y(1)*angle_degrees)^2+y(2)^2)/((sqrt((2*y(1)*angle_degrees)^2+y(2)^2))+w*(2*y(2)^2+4*y(1)^2*angle_degrees^2)))*(2*angle_degrees*Re*A2*(1-phi1)^2.5*(1-phi2)^2.5*y(1)*y(2)+(4-A3*(1-phi1)^2.5*(1-phi2)^2.5*(Ha)^2)*y(2)*angle_degrees^2+((w*(sqrt(2*y(1)*angle_degrees)^2+y(2)^2))*((16*y(1)^3*angle_degrees^4*+8*y(1)*y(2)^2*angle_degrees^2+2*y(2)^2*y(3)+4*y(1)^2*y(3)*angle_degrees^2)/(4*y(1)*y(2)*angle_degrees^2+y(2)*y(3)))+((1/((2*y(1)*angle_degrees)^2*+y(2)^2))*(80*y(1)^2*y(2)*angle_degrees^4+32*y(1)*y(2)*y(3)*angle_degrees^2+8*y(2)^3*angle_degrees^2+4*y(2)*y(3)^2))))
%-(sqrt((2 * y(1) * angle_degrees)^2 + y(2)^2) /(sqrt((2 * y(1) * angle_degrees)^2 + y(2)^2) + w * (2 * y(2)^2 + 4 * y(1)^2 * angle_degrees^2)))*(2*angle_degrees *Re*A2*(1 – phi1)^2.5*(1 – phi2)^2.5 * y(1) * y(2) +(4 – A3 * (1 – phi1)^2.5 * (1 – phi2)^2.5 * (Ha)^2) * y(2) * angle_degrees^2 +((w * (sqrt(2 * y(1) * angle_degrees)^2 + y(2)^2)) *((16 * y(1)^3 * angle_degrees^4 + 8 * y(1) * y(2)^2 * angle_degrees^2 + 2 * y(2)^2 * y(3) +4 * y(1)^2 * y(3) * angle_degrees^2) /(4 * y(1) * y(2) * angle_degrees^2 + y(2) * y(3)) +((1 / ((2 * y(1) * angle_degrees)^2 + y(2)^2)) *(80 * y(1)^2 * y(2) * angle_degrees^4 + 32 * y(1) * y(2) * y(3) * angle_degrees^2+8 * y(2)^3 * angle_degrees^2 + 4 * y(2) * y(3)^2)));
y(5)
(-1/A5)*((E*Pr*A1)/(1-phi1)^2.5*(1-phi2)^2.5)*((4*y(1)^2*angle_degrees^2+y(2)^2)+w*((4*y(1)^2*angle_degrees^2+y(2)^2)^3/2))]
end
function res = williambc(ya,yb,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,~,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2)
res =[ya(1)-1;
ya(2);
ya(5);
yb(1);
yb(4)-1;];
hold on
end
grid on
end william()
function william
clc
clear all format long
w=1; %wlmsn
Ha=0.1;
Re=0.4;
angle_degrees=0.1; %omega N,a,Ha,Re,angle_degrees,E,Pr
E=0.1; %Ec
Pr=0.2; %0.01
phi1=0.001;%0.02,0.03
phi2=0.001;%0.03,0.2
rof=997.1;
ro1=8933;
ro2=3970;
rocpf=4179;
rocp1= 385;
rocp2= 765;
kf=0.613;
k1=401;
k2=40
sigmaf=0.05;
sigma1=5.96*10^7;
sigma2=3.69*10^7;
A1=(phi2*rocp2)/rocpf+ (1-phi2)*((1-phi1)+(rocp1*phi1)/rocpf);
A2=((1-phi2)*((1-phi1)+(ro1*phi1)/rof)+(ro2*phi2)/rof);
A= ((sigma1*(1-2*(phi1)) + 2*sigmaf*(1-phi1))/(sigma1*(1-phi1) + 2*sigmaf*(1+phi1))); %sigmaf
A3=((sigma2*(1+2*(phi2))+2*(1-phi2)*A)/(sigma2*(1-phi2)+(2+phi2)*A))*A;
%A3=((sigma2+2*(1-phi2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1))+2*phi2*sigma2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1)))/(sigma2+2*(1+phi2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1))-phi2*sigma2);
A4=((1-phi1)^-2.5)*((1-phi2)^-2.5); %meuf
A5=(((2 * (1 + phi1) * (2 * kf – 2 * phi2 * (k2 – kf) + k2)) / (2 * kf + phi2 * (k2 – kf) + k2) + ((1 – 2 * phi1) * k1) / kf) / (2 – phi1)) * ((2 * kf – 2 * phi2 * (k2 – kf) + k2) / (2 * kf + phi2 * (k2 – kf) + k2)) + ((1 + phi1) * k1) / kf;
infinity=1;
solinit = bvpinit(linspace(0,infinity,20),zeros(5,1));
options=bvpset(‘Stats’,’on’,’RelTol’,1e-6);
lines={‘k’,’r’,’g’,’m’,’k–‘,’r–‘,’g–‘,’b–‘,’y’,’m’,’k’,’b’};
Ha=0.1;
sol1 = bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.3;
sol2 =bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.5;
sol3 =bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.7;
sol4= bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
figure(1);
plot(sol1.x,sol1.y(1,:),lines{1},sol2.x,sol2.y(1,:),lines{2},sol3.x,sol3.y(1,:),lines{3},sol4.x,sol4.y(1,:),lines{4},’LineWidth’,3,’MarkerSize’,16,’linestyle’,’-‘);
xlabel(‘zeta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
ylabel(‘eta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
grid on
hold on
figure(2);
plot(sol1.x,sol1.y(4,:),lines{1},sol2.x,sol2.y(4,:),lines{2},sol3.x,sol3.y(4,:),lines{3},sol4.x,sol4.y(4,:),lines{4},’LineWidth’,3,’MarkerSize’,16,’linestyle’,’-‘);
xlabel(‘zeta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
ylabel(‘kappa’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
grid on
hold on
y1 = sol1.y;
y2 = sol2.y;
function dydx = williamode(x,y,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2)
dydx =zeros(5,1);
dydx = [y(2)
y(3)
%-(sqrt((2*y(1)*angle_degrees)^2 + y(2)^2) / (sqrt((2*y(1)*angle_degrees)^2 + y(2)^2) + w * (2 * y(2)^2 + 4 * y(1)^2 * angle_degrees^2))) * (2 * angle_degrees * Re * A2 * (1 – phi1)^2.5 * (1 – phi2)^2.5 * y(1) * y(2)+(4-A3*(1-phi1)^2.5*(1-phi2)^2.5*(Ha)^2)*y(2)*angle_degrees^2+(w*(sqrt(2*y(1)*angle_degrees)^2+y(2)^2)*((16*y(1)^3*angle_degrees^4*+8*y(1)*y(2)^2*angle_degrees^2+2*y(2)^2*y(3)+4*y(1)^2*y(3)*angle_degrees^2)/(4*y(1)*y(2)*angle_degrees^2+y(2)*y(3))+(1/((2*y(1)*angle_degrees)^2*+y(2)^2))*(80*y(1)^2*y(2)*angle_degrees^4+32*y(1)*y(2)*y(3)*angle_degrees^2+8*y(2)^3*angle_degrees^2+4*y(2)*y(3)^2)));
-(sqrt((2*y(1)*angle_degrees)^2+y(2)^2)/((sqrt((2*y(1)*angle_degrees)^2+y(2)^2))+w*(2*y(2)^2+4*y(1)^2*angle_degrees^2)))*(2*angle_degrees*Re*A2*(1-phi1)^2.5*(1-phi2)^2.5*y(1)*y(2)+(4-A3*(1-phi1)^2.5*(1-phi2)^2.5*(Ha)^2)*y(2)*angle_degrees^2+((w*(sqrt(2*y(1)*angle_degrees)^2+y(2)^2))*((16*y(1)^3*angle_degrees^4*+8*y(1)*y(2)^2*angle_degrees^2+2*y(2)^2*y(3)+4*y(1)^2*y(3)*angle_degrees^2)/(4*y(1)*y(2)*angle_degrees^2+y(2)*y(3)))+((1/((2*y(1)*angle_degrees)^2*+y(2)^2))*(80*y(1)^2*y(2)*angle_degrees^4+32*y(1)*y(2)*y(3)*angle_degrees^2+8*y(2)^3*angle_degrees^2+4*y(2)*y(3)^2))))
%-(sqrt((2 * y(1) * angle_degrees)^2 + y(2)^2) /(sqrt((2 * y(1) * angle_degrees)^2 + y(2)^2) + w * (2 * y(2)^2 + 4 * y(1)^2 * angle_degrees^2)))*(2*angle_degrees *Re*A2*(1 – phi1)^2.5*(1 – phi2)^2.5 * y(1) * y(2) +(4 – A3 * (1 – phi1)^2.5 * (1 – phi2)^2.5 * (Ha)^2) * y(2) * angle_degrees^2 +((w * (sqrt(2 * y(1) * angle_degrees)^2 + y(2)^2)) *((16 * y(1)^3 * angle_degrees^4 + 8 * y(1) * y(2)^2 * angle_degrees^2 + 2 * y(2)^2 * y(3) +4 * y(1)^2 * y(3) * angle_degrees^2) /(4 * y(1) * y(2) * angle_degrees^2 + y(2) * y(3)) +((1 / ((2 * y(1) * angle_degrees)^2 + y(2)^2)) *(80 * y(1)^2 * y(2) * angle_degrees^4 + 32 * y(1) * y(2) * y(3) * angle_degrees^2+8 * y(2)^3 * angle_degrees^2 + 4 * y(2) * y(3)^2)));
y(5)
(-1/A5)*((E*Pr*A1)/(1-phi1)^2.5*(1-phi2)^2.5)*((4*y(1)^2*angle_degrees^2+y(2)^2)+w*((4*y(1)^2*angle_degrees^2+y(2)^2)^3/2))]
end
function res = williambc(ya,yb,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,~,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2)
res =[ya(1)-1;
ya(2);
ya(5);
yb(1);
yb(4)-1;];
hold on
end
grid on
end remove singular jacobin error MATLAB Answers — New Questions
Are the full models available for vehicle dynamic blocks?
I’m trying to use the blocks in the Vehicle Dynamics Blockset, but there’s not quite enough in the documentation for me to understand the full model being used for various blocks.
For example, in the Vehicle Body 3 DOF block, I’m trying to derive complete equations of motion from the documentation, but the documentation only seems to include information on the forces and some accelerations.
It would be very nice if there was clear information available describing how the vehicle’s position and orientation changes with each time step, or how yaw rate is calculated. I tried looking under the mask of the block to see if this would provide any more information, but it seems like the underlying code is protected.
In short, I’m looking for a clearer understanding of how the outputs are calculated from the inputs, but the documentation doesn’t really organize the equations this way, and it seems like some helpful information is left out.
Is there any more information available for these models?I’m trying to use the blocks in the Vehicle Dynamics Blockset, but there’s not quite enough in the documentation for me to understand the full model being used for various blocks.
For example, in the Vehicle Body 3 DOF block, I’m trying to derive complete equations of motion from the documentation, but the documentation only seems to include information on the forces and some accelerations.
It would be very nice if there was clear information available describing how the vehicle’s position and orientation changes with each time step, or how yaw rate is calculated. I tried looking under the mask of the block to see if this would provide any more information, but it seems like the underlying code is protected.
In short, I’m looking for a clearer understanding of how the outputs are calculated from the inputs, but the documentation doesn’t really organize the equations this way, and it seems like some helpful information is left out.
Is there any more information available for these models? I’m trying to use the blocks in the Vehicle Dynamics Blockset, but there’s not quite enough in the documentation for me to understand the full model being used for various blocks.
For example, in the Vehicle Body 3 DOF block, I’m trying to derive complete equations of motion from the documentation, but the documentation only seems to include information on the forces and some accelerations.
It would be very nice if there was clear information available describing how the vehicle’s position and orientation changes with each time step, or how yaw rate is calculated. I tried looking under the mask of the block to see if this would provide any more information, but it seems like the underlying code is protected.
In short, I’m looking for a clearer understanding of how the outputs are calculated from the inputs, but the documentation doesn’t really organize the equations this way, and it seems like some helpful information is left out.
Is there any more information available for these models? simulink, vehicle dynamics MATLAB Answers — New Questions
Simulating salient pole synchronous generator runaway condition
Hello, I want to examine the runaway condition for a salient pole synchronous generator. For this, I want to remove the load while the synchronous generator is operating at full load and find the acceleration graph of the rotor and the maximum speed it will reach. How can I design this system? generator values: 850 kVA 400V 6 poleHello, I want to examine the runaway condition for a salient pole synchronous generator. For this, I want to remove the load while the synchronous generator is operating at full load and find the acceleration graph of the rotor and the maximum speed it will reach. How can I design this system? generator values: 850 kVA 400V 6 pole Hello, I want to examine the runaway condition for a salient pole synchronous generator. For this, I want to remove the load while the synchronous generator is operating at full load and find the acceleration graph of the rotor and the maximum speed it will reach. How can I design this system? generator values: 850 kVA 400V 6 pole runaway, simulink, synchronous generator MATLAB Answers — New Questions
Multioutput Regression models for non-linear data
Resistance or capacitance (with voltage) and its frequency range as input and my target or to be predicted is magnitude and phase. As u now magnitude and phase are interdependent data it needs to be predicted together. Most of the regression algorithm is failing to capture the interdependency between magnitude and phase.
Please can u suggest a algorithm which best fit this application/Resistance or capacitance (with voltage) and its frequency range as input and my target or to be predicted is magnitude and phase. As u now magnitude and phase are interdependent data it needs to be predicted together. Most of the regression algorithm is failing to capture the interdependency between magnitude and phase.
Please can u suggest a algorithm which best fit this application/ Resistance or capacitance (with voltage) and its frequency range as input and my target or to be predicted is magnitude and phase. As u now magnitude and phase are interdependent data it needs to be predicted together. Most of the regression algorithm is failing to capture the interdependency between magnitude and phase.
Please can u suggest a algorithm which best fit this application/ non-linear, multioutput, regression MATLAB Answers — New Questions
Code Generation for Delay block generates continuous if statement for loading initial value
Hello, I have the following model:
it is a delay block with that should use the input at the first time step as the value.
In the generated code I see that in the initialize function it is setting "untitled_DW.icLoad = true" such that it loads the value on the first execution. However this generates an if statement that only needs to be checked at the 1st iteration, is it possible to have this load statement in the initialize function such that it is removed from the step the function?
/* Model step function */
void untitled_step(void)
{
/* Delay: ‘<Root>/Delay’ incorporates:
* Inport: ‘<Root>/Input’
*/
if (untitled_DW.icLoad) {
untitled_DW.Delay_DSTATE = untitled_U.Input;
}
/* Outport: ‘<Root>/Out’ incorporates:
* Delay: ‘<Root>/Delay’
*/
untitled_Y.Out = untitled_DW.Delay_DSTATE;
/* Update for Delay: ‘<Root>/Delay’ incorporates:
* Inport: ‘<Root>/Input’
*/
untitled_DW.icLoad = false;
untitled_DW.Delay_DSTATE = untitled_U.Input;
}
/* Model initialize function */
void untitled_initialize(void)
{
/* InitializeConditions for Delay: ‘<Root>/Delay’ */
untitled_DW.icLoad = true;
}Hello, I have the following model:
it is a delay block with that should use the input at the first time step as the value.
In the generated code I see that in the initialize function it is setting "untitled_DW.icLoad = true" such that it loads the value on the first execution. However this generates an if statement that only needs to be checked at the 1st iteration, is it possible to have this load statement in the initialize function such that it is removed from the step the function?
/* Model step function */
void untitled_step(void)
{
/* Delay: ‘<Root>/Delay’ incorporates:
* Inport: ‘<Root>/Input’
*/
if (untitled_DW.icLoad) {
untitled_DW.Delay_DSTATE = untitled_U.Input;
}
/* Outport: ‘<Root>/Out’ incorporates:
* Delay: ‘<Root>/Delay’
*/
untitled_Y.Out = untitled_DW.Delay_DSTATE;
/* Update for Delay: ‘<Root>/Delay’ incorporates:
* Inport: ‘<Root>/Input’
*/
untitled_DW.icLoad = false;
untitled_DW.Delay_DSTATE = untitled_U.Input;
}
/* Model initialize function */
void untitled_initialize(void)
{
/* InitializeConditions for Delay: ‘<Root>/Delay’ */
untitled_DW.icLoad = true;
} Hello, I have the following model:
it is a delay block with that should use the input at the first time step as the value.
In the generated code I see that in the initialize function it is setting "untitled_DW.icLoad = true" such that it loads the value on the first execution. However this generates an if statement that only needs to be checked at the 1st iteration, is it possible to have this load statement in the initialize function such that it is removed from the step the function?
/* Model step function */
void untitled_step(void)
{
/* Delay: ‘<Root>/Delay’ incorporates:
* Inport: ‘<Root>/Input’
*/
if (untitled_DW.icLoad) {
untitled_DW.Delay_DSTATE = untitled_U.Input;
}
/* Outport: ‘<Root>/Out’ incorporates:
* Delay: ‘<Root>/Delay’
*/
untitled_Y.Out = untitled_DW.Delay_DSTATE;
/* Update for Delay: ‘<Root>/Delay’ incorporates:
* Inport: ‘<Root>/Input’
*/
untitled_DW.icLoad = false;
untitled_DW.Delay_DSTATE = untitled_U.Input;
}
/* Model initialize function */
void untitled_initialize(void)
{
/* InitializeConditions for Delay: ‘<Root>/Delay’ */
untitled_DW.icLoad = true;
} embedded coder, delay block MATLAB Answers — New Questions
Publishing /diagnostics ros2 Topic in Simulink
Hello,
I am trying to publish a ROS2 diagnostics topic in Simulink. The topic uses the DiagnosticArray message type, which makes it difficult to use the Bus Assignment block. To address this, I created a custom function for the task. Here is the function I implemented:
function msg = assignNestedArrayMessages(blankMessage)
blankMessage.status_SL_Info.CurrentLength = uint32(2);
blankMessage.status(1).level = uint8(1);
blankMessage.status(2).level = uint8(2);
blankMessage.header.stamp.sec = int32(1);
msg =blankMessage;
end
However, despite the simplicity of the function, I encountered the following error:
One or more signal names in the input bus to block ‘pp/pub_diagnostics/SignalSpecification’ does not match the signal names in the bus specified by the bus object ‘SL_Bus_diagnostic_msgs_DiagnosticArray’ on the block dialog. Signal Specification blocks always treat element name mismatches as errors, regardless of the ‘Element name mismatch’ option setting. Either change the specified bus object or rename the input bus element signals to match the bus object.
I would appreciate it if you could provide guidance on how to resolve this issue.Hello,
I am trying to publish a ROS2 diagnostics topic in Simulink. The topic uses the DiagnosticArray message type, which makes it difficult to use the Bus Assignment block. To address this, I created a custom function for the task. Here is the function I implemented:
function msg = assignNestedArrayMessages(blankMessage)
blankMessage.status_SL_Info.CurrentLength = uint32(2);
blankMessage.status(1).level = uint8(1);
blankMessage.status(2).level = uint8(2);
blankMessage.header.stamp.sec = int32(1);
msg =blankMessage;
end
However, despite the simplicity of the function, I encountered the following error:
One or more signal names in the input bus to block ‘pp/pub_diagnostics/SignalSpecification’ does not match the signal names in the bus specified by the bus object ‘SL_Bus_diagnostic_msgs_DiagnosticArray’ on the block dialog. Signal Specification blocks always treat element name mismatches as errors, regardless of the ‘Element name mismatch’ option setting. Either change the specified bus object or rename the input bus element signals to match the bus object.
I would appreciate it if you could provide guidance on how to resolve this issue. Hello,
I am trying to publish a ROS2 diagnostics topic in Simulink. The topic uses the DiagnosticArray message type, which makes it difficult to use the Bus Assignment block. To address this, I created a custom function for the task. Here is the function I implemented:
function msg = assignNestedArrayMessages(blankMessage)
blankMessage.status_SL_Info.CurrentLength = uint32(2);
blankMessage.status(1).level = uint8(1);
blankMessage.status(2).level = uint8(2);
blankMessage.header.stamp.sec = int32(1);
msg =blankMessage;
end
However, despite the simplicity of the function, I encountered the following error:
One or more signal names in the input bus to block ‘pp/pub_diagnostics/SignalSpecification’ does not match the signal names in the bus specified by the bus object ‘SL_Bus_diagnostic_msgs_DiagnosticArray’ on the block dialog. Signal Specification blocks always treat element name mismatches as errors, regardless of the ‘Element name mismatch’ option setting. Either change the specified bus object or rename the input bus element signals to match the bus object.
I would appreciate it if you could provide guidance on how to resolve this issue. ros2, diagnostics MATLAB Answers — New Questions
trying perform an image classification using RL but facing error, Any suggestion?
clc;
%% Load Dataset
imds = imageDatastore(‘D:2023thesiswaveletImagesSubsetImages’, …
‘IncludeSubfolders’, true, …
‘LabelSource’, ‘foldernames’);
% Ensure the dataset is balanced
DataSetInfo = countEachLabel(imds);
% Split Data into Training and Validation sets
[imdsTrain, imdsValidation] = splitEachLabel(imds, 0.80, ‘randomized’);
%% Load Pretrained Network
net = vgg16;
inputSize = net.Layers(1).InputSize;
% Feature extraction layer
featureLayer = ‘fc7’;
% Augment data to match input size of the network
augimdsTrain = augmentedImageDatastore(inputSize, imdsTrain);
augimdsValidation = augmentedImageDatastore(inputSize, imdsValidation);
% Extract Features using Pretrained CNN
trainFeatures = activations(net, augimdsTrain, featureLayer, ‘OutputAs’, ‘rows’);
validationFeatures = activations(net, augimdsValidation, featureLayer, ‘OutputAs’, ‘rows’);
% Extract labels
trainLabels = grp2idx(imdsTrain.Labels);
validationLabels = grp2idx(imdsValidation.Labels);
%% RL Environment Setup
% Define Observation and Action spaces
numFeatures = size(trainFeatures, 2); % Number of features (e.g., 4096 for ‘fc7’ layer)
ObservationInfo = rlNumericSpec([numFeatures, 1], …
‘LowerLimit’, -inf, ‘UpperLimit’, inf, …
‘Name’, ‘Features’);
ObservationInfo.Description = ‘Feature vector extracted from CNN’;
% Define Action space (each action corresponds to a class label)
ActionInfo = rlFiniteSetSpec(1:max(trainLabels)); % Class labels as actions
ActionInfo.Name = ‘Class Labels’;
% Define Step and Reset functions
stepFunction = @(Action, LoggedSignals) stepFunctionRL(Action, trainFeatures, trainLabels, LoggedSignals);
resetFunction = @() resetFunctionRL(trainFeatures);
% Create RL Environment
env = rlFunctionEnv(ObservationInfo, ActionInfo, stepFunction, resetFunction);
%% Define RL Agent
% Define critic network
statePath = [
featureInputLayer(numFeatures, ‘Normalization’, ‘none’, ‘Name’, ‘state’)
fullyConnectedLayer(128, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(64, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(numel(ActionInfo.Elements), ‘Name’, ‘fcOutput’)]; % Number of actions
criticNet = dlnetwork(layerGraph(statePath));
critic = rlQValueFunction(criticNet, ObservationInfo, ActionInfo, ‘ObservationInputNames’, ‘state’);
% Agent options
agentOpts = rlDQNAgentOptions( …
‘ExperienceBufferLength’, 1e5, …
‘DiscountFactor’, 0.99, …
‘MiniBatchSize’, 64, …
‘TargetSmoothFactor’, 1e-3, …
‘TargetUpdateFrequency’, 4);
agent = rlDQNAgent(critic, agentOpts);
%% Train RL Agent
trainOpts = rlTrainingOptions( …
‘MaxEpisodes’, 500, …
‘MaxStepsPerEpisode’, size(trainFeatures, 1), …
‘Verbose’, true, …
‘Plots’, ‘training-progress’, …
‘StopTrainingCriteria’, ‘EpisodeCount’, …
‘StopTrainingValue’, 500);
trainingStats = train(agent, env);
%% Reset Function
function [InitialObservation, LoggedSignals] = resetFunctionRL(Features)
% Reset function for the RL environment
% This function resets the environment to its initial state at the start
% of each new episode.
% Initialize the LoggedSignals structure (holds environment state)
LoggedSignals = struct();
% Set the initial observation index to the first data point
LoggedSignals.CurrentIndex = 1;
% Fetch the initial observation: the first feature vector
% Ensure that the observation is formatted as a column vector [numFeatures, 1]
InitialObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to column vector
% Check if the initial observation matches the expected size
if size(InitialObservation, 2) ~= 1
error(‘InitialObservation must be a column vector of size [numFeatures, 1]’);
end
% Optionally, initialize any other properties you want in LoggedSignals
% (e.g., additional state variables, environment-specific flags)
LoggedSignals.EpisodeStartTime = datetime(‘now’); % Track the start time for each episode
end
%% Step Function
function [NextObservation, Reward, IsDone, LoggedSignals] = stepFunctionRL(Action, Features, Labels, LoggedSignals)
% Step function for the RL environment
idx = LoggedSignals.CurrentIndex;
% Assign reward based on action correctness
correctLabel = Labels(idx); % Correct label for the current feature
if Action == correctLabel
Reward = 1; % Positive reward for correct classification
else
Reward = -1; % Negative reward for incorrect classification
end
% Update index and check if episode is done
LoggedSignals.CurrentIndex = idx + 1;
IsDone = LoggedSignals.CurrentIndex > size(Features, 1);
% Ensure the next observation is a column vector of size [numFeatures, 1]
if ~IsDone
NextObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to ensure column vector [numFeatures x 1]
else
NextObservation = Features(idx, :)’; % Dummy to avoid dimension mismatch
end
end
AND THIS IS THE ERROR
Error using rl.env.MATLABEnvironment/validateEnvironment (line 58)
Environment ‘ObservationInfo’ does not match observation output from reset function. Check the data type, dimensions, and range.
Error in rl.env.rlFunctionEnv (line 82)
validateEnvironment(this);
Error in rlFunctionEnv (line 45)
env = rl.env.rlFunctionEnv(varargin{:});clc;
%% Load Dataset
imds = imageDatastore(‘D:2023thesiswaveletImagesSubsetImages’, …
‘IncludeSubfolders’, true, …
‘LabelSource’, ‘foldernames’);
% Ensure the dataset is balanced
DataSetInfo = countEachLabel(imds);
% Split Data into Training and Validation sets
[imdsTrain, imdsValidation] = splitEachLabel(imds, 0.80, ‘randomized’);
%% Load Pretrained Network
net = vgg16;
inputSize = net.Layers(1).InputSize;
% Feature extraction layer
featureLayer = ‘fc7’;
% Augment data to match input size of the network
augimdsTrain = augmentedImageDatastore(inputSize, imdsTrain);
augimdsValidation = augmentedImageDatastore(inputSize, imdsValidation);
% Extract Features using Pretrained CNN
trainFeatures = activations(net, augimdsTrain, featureLayer, ‘OutputAs’, ‘rows’);
validationFeatures = activations(net, augimdsValidation, featureLayer, ‘OutputAs’, ‘rows’);
% Extract labels
trainLabels = grp2idx(imdsTrain.Labels);
validationLabels = grp2idx(imdsValidation.Labels);
%% RL Environment Setup
% Define Observation and Action spaces
numFeatures = size(trainFeatures, 2); % Number of features (e.g., 4096 for ‘fc7’ layer)
ObservationInfo = rlNumericSpec([numFeatures, 1], …
‘LowerLimit’, -inf, ‘UpperLimit’, inf, …
‘Name’, ‘Features’);
ObservationInfo.Description = ‘Feature vector extracted from CNN’;
% Define Action space (each action corresponds to a class label)
ActionInfo = rlFiniteSetSpec(1:max(trainLabels)); % Class labels as actions
ActionInfo.Name = ‘Class Labels’;
% Define Step and Reset functions
stepFunction = @(Action, LoggedSignals) stepFunctionRL(Action, trainFeatures, trainLabels, LoggedSignals);
resetFunction = @() resetFunctionRL(trainFeatures);
% Create RL Environment
env = rlFunctionEnv(ObservationInfo, ActionInfo, stepFunction, resetFunction);
%% Define RL Agent
% Define critic network
statePath = [
featureInputLayer(numFeatures, ‘Normalization’, ‘none’, ‘Name’, ‘state’)
fullyConnectedLayer(128, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(64, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(numel(ActionInfo.Elements), ‘Name’, ‘fcOutput’)]; % Number of actions
criticNet = dlnetwork(layerGraph(statePath));
critic = rlQValueFunction(criticNet, ObservationInfo, ActionInfo, ‘ObservationInputNames’, ‘state’);
% Agent options
agentOpts = rlDQNAgentOptions( …
‘ExperienceBufferLength’, 1e5, …
‘DiscountFactor’, 0.99, …
‘MiniBatchSize’, 64, …
‘TargetSmoothFactor’, 1e-3, …
‘TargetUpdateFrequency’, 4);
agent = rlDQNAgent(critic, agentOpts);
%% Train RL Agent
trainOpts = rlTrainingOptions( …
‘MaxEpisodes’, 500, …
‘MaxStepsPerEpisode’, size(trainFeatures, 1), …
‘Verbose’, true, …
‘Plots’, ‘training-progress’, …
‘StopTrainingCriteria’, ‘EpisodeCount’, …
‘StopTrainingValue’, 500);
trainingStats = train(agent, env);
%% Reset Function
function [InitialObservation, LoggedSignals] = resetFunctionRL(Features)
% Reset function for the RL environment
% This function resets the environment to its initial state at the start
% of each new episode.
% Initialize the LoggedSignals structure (holds environment state)
LoggedSignals = struct();
% Set the initial observation index to the first data point
LoggedSignals.CurrentIndex = 1;
% Fetch the initial observation: the first feature vector
% Ensure that the observation is formatted as a column vector [numFeatures, 1]
InitialObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to column vector
% Check if the initial observation matches the expected size
if size(InitialObservation, 2) ~= 1
error(‘InitialObservation must be a column vector of size [numFeatures, 1]’);
end
% Optionally, initialize any other properties you want in LoggedSignals
% (e.g., additional state variables, environment-specific flags)
LoggedSignals.EpisodeStartTime = datetime(‘now’); % Track the start time for each episode
end
%% Step Function
function [NextObservation, Reward, IsDone, LoggedSignals] = stepFunctionRL(Action, Features, Labels, LoggedSignals)
% Step function for the RL environment
idx = LoggedSignals.CurrentIndex;
% Assign reward based on action correctness
correctLabel = Labels(idx); % Correct label for the current feature
if Action == correctLabel
Reward = 1; % Positive reward for correct classification
else
Reward = -1; % Negative reward for incorrect classification
end
% Update index and check if episode is done
LoggedSignals.CurrentIndex = idx + 1;
IsDone = LoggedSignals.CurrentIndex > size(Features, 1);
% Ensure the next observation is a column vector of size [numFeatures, 1]
if ~IsDone
NextObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to ensure column vector [numFeatures x 1]
else
NextObservation = Features(idx, :)’; % Dummy to avoid dimension mismatch
end
end
AND THIS IS THE ERROR
Error using rl.env.MATLABEnvironment/validateEnvironment (line 58)
Environment ‘ObservationInfo’ does not match observation output from reset function. Check the data type, dimensions, and range.
Error in rl.env.rlFunctionEnv (line 82)
validateEnvironment(this);
Error in rlFunctionEnv (line 45)
env = rl.env.rlFunctionEnv(varargin{:}); clc;
%% Load Dataset
imds = imageDatastore(‘D:2023thesiswaveletImagesSubsetImages’, …
‘IncludeSubfolders’, true, …
‘LabelSource’, ‘foldernames’);
% Ensure the dataset is balanced
DataSetInfo = countEachLabel(imds);
% Split Data into Training and Validation sets
[imdsTrain, imdsValidation] = splitEachLabel(imds, 0.80, ‘randomized’);
%% Load Pretrained Network
net = vgg16;
inputSize = net.Layers(1).InputSize;
% Feature extraction layer
featureLayer = ‘fc7’;
% Augment data to match input size of the network
augimdsTrain = augmentedImageDatastore(inputSize, imdsTrain);
augimdsValidation = augmentedImageDatastore(inputSize, imdsValidation);
% Extract Features using Pretrained CNN
trainFeatures = activations(net, augimdsTrain, featureLayer, ‘OutputAs’, ‘rows’);
validationFeatures = activations(net, augimdsValidation, featureLayer, ‘OutputAs’, ‘rows’);
% Extract labels
trainLabels = grp2idx(imdsTrain.Labels);
validationLabels = grp2idx(imdsValidation.Labels);
%% RL Environment Setup
% Define Observation and Action spaces
numFeatures = size(trainFeatures, 2); % Number of features (e.g., 4096 for ‘fc7’ layer)
ObservationInfo = rlNumericSpec([numFeatures, 1], …
‘LowerLimit’, -inf, ‘UpperLimit’, inf, …
‘Name’, ‘Features’);
ObservationInfo.Description = ‘Feature vector extracted from CNN’;
% Define Action space (each action corresponds to a class label)
ActionInfo = rlFiniteSetSpec(1:max(trainLabels)); % Class labels as actions
ActionInfo.Name = ‘Class Labels’;
% Define Step and Reset functions
stepFunction = @(Action, LoggedSignals) stepFunctionRL(Action, trainFeatures, trainLabels, LoggedSignals);
resetFunction = @() resetFunctionRL(trainFeatures);
% Create RL Environment
env = rlFunctionEnv(ObservationInfo, ActionInfo, stepFunction, resetFunction);
%% Define RL Agent
% Define critic network
statePath = [
featureInputLayer(numFeatures, ‘Normalization’, ‘none’, ‘Name’, ‘state’)
fullyConnectedLayer(128, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(64, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(numel(ActionInfo.Elements), ‘Name’, ‘fcOutput’)]; % Number of actions
criticNet = dlnetwork(layerGraph(statePath));
critic = rlQValueFunction(criticNet, ObservationInfo, ActionInfo, ‘ObservationInputNames’, ‘state’);
% Agent options
agentOpts = rlDQNAgentOptions( …
‘ExperienceBufferLength’, 1e5, …
‘DiscountFactor’, 0.99, …
‘MiniBatchSize’, 64, …
‘TargetSmoothFactor’, 1e-3, …
‘TargetUpdateFrequency’, 4);
agent = rlDQNAgent(critic, agentOpts);
%% Train RL Agent
trainOpts = rlTrainingOptions( …
‘MaxEpisodes’, 500, …
‘MaxStepsPerEpisode’, size(trainFeatures, 1), …
‘Verbose’, true, …
‘Plots’, ‘training-progress’, …
‘StopTrainingCriteria’, ‘EpisodeCount’, …
‘StopTrainingValue’, 500);
trainingStats = train(agent, env);
%% Reset Function
function [InitialObservation, LoggedSignals] = resetFunctionRL(Features)
% Reset function for the RL environment
% This function resets the environment to its initial state at the start
% of each new episode.
% Initialize the LoggedSignals structure (holds environment state)
LoggedSignals = struct();
% Set the initial observation index to the first data point
LoggedSignals.CurrentIndex = 1;
% Fetch the initial observation: the first feature vector
% Ensure that the observation is formatted as a column vector [numFeatures, 1]
InitialObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to column vector
% Check if the initial observation matches the expected size
if size(InitialObservation, 2) ~= 1
error(‘InitialObservation must be a column vector of size [numFeatures, 1]’);
end
% Optionally, initialize any other properties you want in LoggedSignals
% (e.g., additional state variables, environment-specific flags)
LoggedSignals.EpisodeStartTime = datetime(‘now’); % Track the start time for each episode
end
%% Step Function
function [NextObservation, Reward, IsDone, LoggedSignals] = stepFunctionRL(Action, Features, Labels, LoggedSignals)
% Step function for the RL environment
idx = LoggedSignals.CurrentIndex;
% Assign reward based on action correctness
correctLabel = Labels(idx); % Correct label for the current feature
if Action == correctLabel
Reward = 1; % Positive reward for correct classification
else
Reward = -1; % Negative reward for incorrect classification
end
% Update index and check if episode is done
LoggedSignals.CurrentIndex = idx + 1;
IsDone = LoggedSignals.CurrentIndex > size(Features, 1);
% Ensure the next observation is a column vector of size [numFeatures, 1]
if ~IsDone
NextObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to ensure column vector [numFeatures x 1]
else
NextObservation = Features(idx, :)’; % Dummy to avoid dimension mismatch
end
end
AND THIS IS THE ERROR
Error using rl.env.MATLABEnvironment/validateEnvironment (line 58)
Environment ‘ObservationInfo’ does not match observation output from reset function. Check the data type, dimensions, and range.
Error in rl.env.rlFunctionEnv (line 82)
validateEnvironment(this);
Error in rlFunctionEnv (line 45)
env = rl.env.rlFunctionEnv(varargin{:}); rl, image-classification MATLAB Answers — New Questions
error in testing matpower
hi everyone, I want to install matpower 6.0 in my matlab 2019b but after I install it same as instruction I get errors in testing it.
when I write test_matpower in command window I recieve these errors.
please help me to install it successfully.
>> test_matpower
t_test_fcns………….ok
t_nested_struct_copy….ok
t_feval_w_path……….ok
t_mpoption…………..ok
t_loadcase…………..Error using save
Unable to write file t_mat9_opf.mat:
permission denied.
Error in t_loadcase (line 40)
eval([‘save ‘ matfile ‘.mat baseMVA bus
gen branch areas gencost’]);
Error in t_run_tests (line 58)
feval( test_names{k}, ~verbose );
Error in test_matpower (line 128)
t_run_tests( tests, verbose );hi everyone, I want to install matpower 6.0 in my matlab 2019b but after I install it same as instruction I get errors in testing it.
when I write test_matpower in command window I recieve these errors.
please help me to install it successfully.
>> test_matpower
t_test_fcns………….ok
t_nested_struct_copy….ok
t_feval_w_path……….ok
t_mpoption…………..ok
t_loadcase…………..Error using save
Unable to write file t_mat9_opf.mat:
permission denied.
Error in t_loadcase (line 40)
eval([‘save ‘ matfile ‘.mat baseMVA bus
gen branch areas gencost’]);
Error in t_run_tests (line 58)
feval( test_names{k}, ~verbose );
Error in test_matpower (line 128)
t_run_tests( tests, verbose ); hi everyone, I want to install matpower 6.0 in my matlab 2019b but after I install it same as instruction I get errors in testing it.
when I write test_matpower in command window I recieve these errors.
please help me to install it successfully.
>> test_matpower
t_test_fcns………….ok
t_nested_struct_copy….ok
t_feval_w_path……….ok
t_mpoption…………..ok
t_loadcase…………..Error using save
Unable to write file t_mat9_opf.mat:
permission denied.
Error in t_loadcase (line 40)
eval([‘save ‘ matfile ‘.mat baseMVA bus
gen branch areas gencost’]);
Error in t_run_tests (line 58)
feval( test_names{k}, ~verbose );
Error in test_matpower (line 128)
t_run_tests( tests, verbose ); matpower MATLAB Answers — New Questions
how to identify the cracks from the image
<</matlabcentral/answers/uploaded_files/129987/el2.jpg>><</matlabcentral/answers/uploaded_files/129987/el2.jpg>> <</matlabcentral/answers/uploaded_files/129987/el2.jpg>> ir image, cracks, image segmentation, tiles MATLAB Answers — New Questions
Crack Detection
I have problem for detection for surface ceramics image, how i can detect crack surface , pls give me some advice. this my code for detect crack surface
function [img1_array, img2_array,img3_array, img4_array,Zme]= DefectScan(input_path,input_path2);
% clear all;
% close all;
I = imread(input_path2);
J = imread(input_path);
I = rgb2gray(I);
J = rgb2gray(J);
% f=figure,imshow(I);
% g=figure,imshow(J);
hy = fspecial(‘sobel’);
hx = hy’;
Iy = imfilter(double(I), hy, ‘replicate’);
Ix = imfilter(double(I), hx, ‘replicate’);
ey = fspecial(‘sobel’);
fx = ey’;
Jy = imfilter(double(J), ey, ‘replicate’);
Jx = imfilter(double(J), fx, ‘replicate’);
gradmag = sqrt(Ix.^2 + Iy.^2);
gradmag2 = sqrt(Jx.^2 + Jy.^2);
K=figure,imshow(gradmag,[]);
L=figure,imshow(gradmag2,[]);
set(K, ‘visible’,’off’);
set(L, ‘visible’,’off’);
filename = ‘temp_file.jpg’
filename2 = ‘temp_file2.jpg’
saveas(K, filename)
saveas(L, filename2)
i1 = imread(filename)
i2 = imread(filename2)
delete(filename)
delete(filename2)
[x, y, rgb] = ind2sub([size(i1,1) size(i1,2) size(i1,3)], find(i1 ~= 255));
A = i1(min(x):max(x)-1,min(y):max(y)-1,:);
[x, y, rgb] = ind2sub([size(i2,1) size(i2,2) size(i2,3)], find(i2 ~= 255));
B = i2(min(x):max(x)-1,min(y):max(y)-1,:);
A = rgb2gray(A)
B = rgb2gray(B)
I = edge(A,’sobel’)
J = edge(B,’sobel’)I have problem for detection for surface ceramics image, how i can detect crack surface , pls give me some advice. this my code for detect crack surface
function [img1_array, img2_array,img3_array, img4_array,Zme]= DefectScan(input_path,input_path2);
% clear all;
% close all;
I = imread(input_path2);
J = imread(input_path);
I = rgb2gray(I);
J = rgb2gray(J);
% f=figure,imshow(I);
% g=figure,imshow(J);
hy = fspecial(‘sobel’);
hx = hy’;
Iy = imfilter(double(I), hy, ‘replicate’);
Ix = imfilter(double(I), hx, ‘replicate’);
ey = fspecial(‘sobel’);
fx = ey’;
Jy = imfilter(double(J), ey, ‘replicate’);
Jx = imfilter(double(J), fx, ‘replicate’);
gradmag = sqrt(Ix.^2 + Iy.^2);
gradmag2 = sqrt(Jx.^2 + Jy.^2);
K=figure,imshow(gradmag,[]);
L=figure,imshow(gradmag2,[]);
set(K, ‘visible’,’off’);
set(L, ‘visible’,’off’);
filename = ‘temp_file.jpg’
filename2 = ‘temp_file2.jpg’
saveas(K, filename)
saveas(L, filename2)
i1 = imread(filename)
i2 = imread(filename2)
delete(filename)
delete(filename2)
[x, y, rgb] = ind2sub([size(i1,1) size(i1,2) size(i1,3)], find(i1 ~= 255));
A = i1(min(x):max(x)-1,min(y):max(y)-1,:);
[x, y, rgb] = ind2sub([size(i2,1) size(i2,2) size(i2,3)], find(i2 ~= 255));
B = i2(min(x):max(x)-1,min(y):max(y)-1,:);
A = rgb2gray(A)
B = rgb2gray(B)
I = edge(A,’sobel’)
J = edge(B,’sobel’) I have problem for detection for surface ceramics image, how i can detect crack surface , pls give me some advice. this my code for detect crack surface
function [img1_array, img2_array,img3_array, img4_array,Zme]= DefectScan(input_path,input_path2);
% clear all;
% close all;
I = imread(input_path2);
J = imread(input_path);
I = rgb2gray(I);
J = rgb2gray(J);
% f=figure,imshow(I);
% g=figure,imshow(J);
hy = fspecial(‘sobel’);
hx = hy’;
Iy = imfilter(double(I), hy, ‘replicate’);
Ix = imfilter(double(I), hx, ‘replicate’);
ey = fspecial(‘sobel’);
fx = ey’;
Jy = imfilter(double(J), ey, ‘replicate’);
Jx = imfilter(double(J), fx, ‘replicate’);
gradmag = sqrt(Ix.^2 + Iy.^2);
gradmag2 = sqrt(Jx.^2 + Jy.^2);
K=figure,imshow(gradmag,[]);
L=figure,imshow(gradmag2,[]);
set(K, ‘visible’,’off’);
set(L, ‘visible’,’off’);
filename = ‘temp_file.jpg’
filename2 = ‘temp_file2.jpg’
saveas(K, filename)
saveas(L, filename2)
i1 = imread(filename)
i2 = imread(filename2)
delete(filename)
delete(filename2)
[x, y, rgb] = ind2sub([size(i1,1) size(i1,2) size(i1,3)], find(i1 ~= 255));
A = i1(min(x):max(x)-1,min(y):max(y)-1,:);
[x, y, rgb] = ind2sub([size(i2,1) size(i2,2) size(i2,3)], find(i2 ~= 255));
B = i2(min(x):max(x)-1,min(y):max(y)-1,:);
A = rgb2gray(A)
B = rgb2gray(B)
I = edge(A,’sobel’)
J = edge(B,’sobel’) detection crack surface, doit4me, sendit2me MATLAB Answers — New Questions
Crack detection on concrete
Hi, i have problem in measuring the length and width the crack image.
i have follow the code but it only measure straight line (endpoint). I want the measurement by following the crack pattern. Please help me on this.
%load image
path=imgetfile();
originalImage1=imread(path);
imshow(originalImage1);
%image to grayscale
originalImage = rgb2gray(originalImage1);
figure
imshow(originalImage);
%treshold
thresholdValue = 100;
binaryImage = originalImage > thresholdValue;
binaryImage = imfill(binaryImage, ‘holes’);
hold on;
% maxYValue = ylim;
% line([thresholdValue, thresholdValue], maxYValue, ‘Color’, ‘r’);
% annotationText = sprintf(‘Thresholded at %d gray levels’, thresholdValue);
% text(double(thresholdValue + 5), double(0.5 * maxYValue(2)), annotationText, ‘FontSize’, 10, ‘Color’, [0 .5 0]);
% text(double(thresholdValue – 70), double(0.94 * maxYValue(2)), ‘Background’, ‘FontSize’, 10, ‘Color’, [0 0 .5]);
% text(double(thresholdValue + 50), double(0.94 * maxYValue(2)), ‘Foreground’, ‘FontSize’, 10, ‘Color’, [0 0 .5]);
figure
imshow(binaryImage);
% bw = bwareaopen(binaryImage,100,8);
bw= bwareaopen(binaryImage, round(0.1*numel(binaryImage)));
figure
imshow(bw)
g=bwmorph(bw,’clean’);
figure
imshow(g);
% %labeled image (on hold)
labeledImage = bwlabel(g,4);
figure
imshow(labeledImage, []);
%colored label image
coloredLabels = label2rgb (labeledImage, ‘hsv’, ‘k’, ‘shuffle’);
figure
imshow(coloredLabels);
axis image;
%blobmeasurement
blobMeasurements = regionprops(labeledImage, originalImage, ‘all’);
numberOfBlobs = size(blobMeasurements, 1);
figure
imshow(originalImage);
axis image; % Make sure image is not artificially stretched because of screen’s aspect ratio.
hold on;
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
for k = 1 : numberOfBoundaries
thisBoundary = boundaries{k};
plot(thisBoundary(:,2), thisBoundary(:,1), ‘g’, ‘LineWidth’, 2);
end
hold off;
% Measure the area
measurements = regionprops(labeledImage, ‘Area’);
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
for blobIndex = 1 : numberOfBoundaries
thisBoundary = boundaries{blobIndex};
x = thisBoundary(:, 2); % x = columns.
y = thisBoundary(:, 1); % y = rows.
% Find which two bounary points are farthest from each other.
maxDistance = -inf;
for k = 1 : length(x)
distances = sqrt( (x(k) – x) .^ 2 + (y(k) – y) .^ 2 );
[thisMaxDistance, indexOfMaxDistance] = max(distances);
if thisMaxDistance > maxDistance
maxDistance = thisMaxDistance;
index1 = k;
index2 = indexOfMaxDistance;
end
end
% Find the midpoint of the line.
xMidPoint = mean([x(index1), x(index2)]);
yMidPoint = mean([y(index1), y(index2)]);
longSlope = (y(index1) – y(index2)) / (x(index1) – x(index2))
perpendicularSlope = -1/longSlope
% Use point slope formula (y-ym) = slope * (x – xm) to get points
y1 = perpendicularSlope * (1 – xMidPoint) + yMidPoint;
y2 = perpendicularSlope * (columns – xMidPoint) + yMidPoint;
% Get the profile perpendicular to the midpoint so we can find out when if first enters and last leaves the object.
[cx,cy,c] = improfile(binaryImage,[1, columns], [y1, y2], 1000);
% Get rid of NAN’s that occur when the line’s endpoints go above or below the image.
c(isnan(c)) = 0;
firstIndex = find(c, 1, ‘first’);
lastIndex = find(c, 1, ‘last’);
% Compute the distance of that perpendicular width.
perpendicularWidth = sqrt( (cx(firstIndex) – cx(lastIndex)) .^ 2 + (cy(firstIndex) – cy(lastIndex)) .^ 2 );
% Get the average perpendicular width. This will approximately be the area divided by the longest length.
averageWidth = measurements(blobIndex).Area / maxDistance;
% Plot the boundaries, line, and midpoints over the two images.
% Plot the boundary over the gray scale image
subplot(2, 2, 3);
plot(x, y, ‘y-‘, ‘LineWidth’, 3);
% For this blob, put a line between the points farthest away from each other.
line([x(index1), x(index2)], [y(index1), y(index2)], ‘Color’, ‘r’, ‘LineWidth’, 3);
plot(xMidPoint, yMidPoint, ‘r*’, ‘MarkerSize’, 15, ‘LineWidth’, 2);
% Plot perpendicular line. Make it green across the whole image but magenta inside the blob.
line([1, columns], [y1, y2], ‘Color’, ‘g’, ‘LineWidth’, 3);
line([cx(firstIndex), cx(lastIndex)], [cy(firstIndex), cy(lastIndex)], ‘Color’, ‘m’, ‘LineWidth’, 3);
% Plot the boundary over the binary image
subplot(2, 2, 4);
plot(x, y, ‘y-‘, ‘LineWidth’, 3);
% For this blob, put a line between the points farthest away from each other.
line([x(index1), x(index2)], [y(index1), y(index2)], ‘Color’, ‘r’, ‘LineWidth’, 3);
plot(xMidPoint, yMidPoint, ‘r*’, ‘MarkerSize’, 15, ‘LineWidth’, 2);
% Plot perpendicular line. Make it green across the whole image but magenta inside the blob.
line([1, columns], [y1, y2], ‘Color’, ‘g’, ‘LineWidth’, 3);
line([cx(firstIndex), cx(lastIndex)], [cy(firstIndex), cy(lastIndex)], ‘Color’, ‘m’, ‘LineWidth’, 3);
message = sprintf(‘The longest line is red.nPerpendicular to that, at the midpoint, is green.nMax distance for blob #%d = %.2fnPerpendicular distance at midpoint = %.2fnAverage perpendicular width = %.2f (approximatelynArea = %d’, …
blobIndex, maxDistance, perpendicularWidth, averageWidth, measurements(blobIndex).Area);
fprintf(‘%sn’, message);
uiwait(helpdlg(message));
end
hold off;Hi, i have problem in measuring the length and width the crack image.
i have follow the code but it only measure straight line (endpoint). I want the measurement by following the crack pattern. Please help me on this.
%load image
path=imgetfile();
originalImage1=imread(path);
imshow(originalImage1);
%image to grayscale
originalImage = rgb2gray(originalImage1);
figure
imshow(originalImage);
%treshold
thresholdValue = 100;
binaryImage = originalImage > thresholdValue;
binaryImage = imfill(binaryImage, ‘holes’);
hold on;
% maxYValue = ylim;
% line([thresholdValue, thresholdValue], maxYValue, ‘Color’, ‘r’);
% annotationText = sprintf(‘Thresholded at %d gray levels’, thresholdValue);
% text(double(thresholdValue + 5), double(0.5 * maxYValue(2)), annotationText, ‘FontSize’, 10, ‘Color’, [0 .5 0]);
% text(double(thresholdValue – 70), double(0.94 * maxYValue(2)), ‘Background’, ‘FontSize’, 10, ‘Color’, [0 0 .5]);
% text(double(thresholdValue + 50), double(0.94 * maxYValue(2)), ‘Foreground’, ‘FontSize’, 10, ‘Color’, [0 0 .5]);
figure
imshow(binaryImage);
% bw = bwareaopen(binaryImage,100,8);
bw= bwareaopen(binaryImage, round(0.1*numel(binaryImage)));
figure
imshow(bw)
g=bwmorph(bw,’clean’);
figure
imshow(g);
% %labeled image (on hold)
labeledImage = bwlabel(g,4);
figure
imshow(labeledImage, []);
%colored label image
coloredLabels = label2rgb (labeledImage, ‘hsv’, ‘k’, ‘shuffle’);
figure
imshow(coloredLabels);
axis image;
%blobmeasurement
blobMeasurements = regionprops(labeledImage, originalImage, ‘all’);
numberOfBlobs = size(blobMeasurements, 1);
figure
imshow(originalImage);
axis image; % Make sure image is not artificially stretched because of screen’s aspect ratio.
hold on;
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
for k = 1 : numberOfBoundaries
thisBoundary = boundaries{k};
plot(thisBoundary(:,2), thisBoundary(:,1), ‘g’, ‘LineWidth’, 2);
end
hold off;
% Measure the area
measurements = regionprops(labeledImage, ‘Area’);
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
for blobIndex = 1 : numberOfBoundaries
thisBoundary = boundaries{blobIndex};
x = thisBoundary(:, 2); % x = columns.
y = thisBoundary(:, 1); % y = rows.
% Find which two bounary points are farthest from each other.
maxDistance = -inf;
for k = 1 : length(x)
distances = sqrt( (x(k) – x) .^ 2 + (y(k) – y) .^ 2 );
[thisMaxDistance, indexOfMaxDistance] = max(distances);
if thisMaxDistance > maxDistance
maxDistance = thisMaxDistance;
index1 = k;
index2 = indexOfMaxDistance;
end
end
% Find the midpoint of the line.
xMidPoint = mean([x(index1), x(index2)]);
yMidPoint = mean([y(index1), y(index2)]);
longSlope = (y(index1) – y(index2)) / (x(index1) – x(index2))
perpendicularSlope = -1/longSlope
% Use point slope formula (y-ym) = slope * (x – xm) to get points
y1 = perpendicularSlope * (1 – xMidPoint) + yMidPoint;
y2 = perpendicularSlope * (columns – xMidPoint) + yMidPoint;
% Get the profile perpendicular to the midpoint so we can find out when if first enters and last leaves the object.
[cx,cy,c] = improfile(binaryImage,[1, columns], [y1, y2], 1000);
% Get rid of NAN’s that occur when the line’s endpoints go above or below the image.
c(isnan(c)) = 0;
firstIndex = find(c, 1, ‘first’);
lastIndex = find(c, 1, ‘last’);
% Compute the distance of that perpendicular width.
perpendicularWidth = sqrt( (cx(firstIndex) – cx(lastIndex)) .^ 2 + (cy(firstIndex) – cy(lastIndex)) .^ 2 );
% Get the average perpendicular width. This will approximately be the area divided by the longest length.
averageWidth = measurements(blobIndex).Area / maxDistance;
% Plot the boundaries, line, and midpoints over the two images.
% Plot the boundary over the gray scale image
subplot(2, 2, 3);
plot(x, y, ‘y-‘, ‘LineWidth’, 3);
% For this blob, put a line between the points farthest away from each other.
line([x(index1), x(index2)], [y(index1), y(index2)], ‘Color’, ‘r’, ‘LineWidth’, 3);
plot(xMidPoint, yMidPoint, ‘r*’, ‘MarkerSize’, 15, ‘LineWidth’, 2);
% Plot perpendicular line. Make it green across the whole image but magenta inside the blob.
line([1, columns], [y1, y2], ‘Color’, ‘g’, ‘LineWidth’, 3);
line([cx(firstIndex), cx(lastIndex)], [cy(firstIndex), cy(lastIndex)], ‘Color’, ‘m’, ‘LineWidth’, 3);
% Plot the boundary over the binary image
subplot(2, 2, 4);
plot(x, y, ‘y-‘, ‘LineWidth’, 3);
% For this blob, put a line between the points farthest away from each other.
line([x(index1), x(index2)], [y(index1), y(index2)], ‘Color’, ‘r’, ‘LineWidth’, 3);
plot(xMidPoint, yMidPoint, ‘r*’, ‘MarkerSize’, 15, ‘LineWidth’, 2);
% Plot perpendicular line. Make it green across the whole image but magenta inside the blob.
line([1, columns], [y1, y2], ‘Color’, ‘g’, ‘LineWidth’, 3);
line([cx(firstIndex), cx(lastIndex)], [cy(firstIndex), cy(lastIndex)], ‘Color’, ‘m’, ‘LineWidth’, 3);
message = sprintf(‘The longest line is red.nPerpendicular to that, at the midpoint, is green.nMax distance for blob #%d = %.2fnPerpendicular distance at midpoint = %.2fnAverage perpendicular width = %.2f (approximatelynArea = %d’, …
blobIndex, maxDistance, perpendicularWidth, averageWidth, measurements(blobIndex).Area);
fprintf(‘%sn’, message);
uiwait(helpdlg(message));
end
hold off; Hi, i have problem in measuring the length and width the crack image.
i have follow the code but it only measure straight line (endpoint). I want the measurement by following the crack pattern. Please help me on this.
%load image
path=imgetfile();
originalImage1=imread(path);
imshow(originalImage1);
%image to grayscale
originalImage = rgb2gray(originalImage1);
figure
imshow(originalImage);
%treshold
thresholdValue = 100;
binaryImage = originalImage > thresholdValue;
binaryImage = imfill(binaryImage, ‘holes’);
hold on;
% maxYValue = ylim;
% line([thresholdValue, thresholdValue], maxYValue, ‘Color’, ‘r’);
% annotationText = sprintf(‘Thresholded at %d gray levels’, thresholdValue);
% text(double(thresholdValue + 5), double(0.5 * maxYValue(2)), annotationText, ‘FontSize’, 10, ‘Color’, [0 .5 0]);
% text(double(thresholdValue – 70), double(0.94 * maxYValue(2)), ‘Background’, ‘FontSize’, 10, ‘Color’, [0 0 .5]);
% text(double(thresholdValue + 50), double(0.94 * maxYValue(2)), ‘Foreground’, ‘FontSize’, 10, ‘Color’, [0 0 .5]);
figure
imshow(binaryImage);
% bw = bwareaopen(binaryImage,100,8);
bw= bwareaopen(binaryImage, round(0.1*numel(binaryImage)));
figure
imshow(bw)
g=bwmorph(bw,’clean’);
figure
imshow(g);
% %labeled image (on hold)
labeledImage = bwlabel(g,4);
figure
imshow(labeledImage, []);
%colored label image
coloredLabels = label2rgb (labeledImage, ‘hsv’, ‘k’, ‘shuffle’);
figure
imshow(coloredLabels);
axis image;
%blobmeasurement
blobMeasurements = regionprops(labeledImage, originalImage, ‘all’);
numberOfBlobs = size(blobMeasurements, 1);
figure
imshow(originalImage);
axis image; % Make sure image is not artificially stretched because of screen’s aspect ratio.
hold on;
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
for k = 1 : numberOfBoundaries
thisBoundary = boundaries{k};
plot(thisBoundary(:,2), thisBoundary(:,1), ‘g’, ‘LineWidth’, 2);
end
hold off;
% Measure the area
measurements = regionprops(labeledImage, ‘Area’);
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
for blobIndex = 1 : numberOfBoundaries
thisBoundary = boundaries{blobIndex};
x = thisBoundary(:, 2); % x = columns.
y = thisBoundary(:, 1); % y = rows.
% Find which two bounary points are farthest from each other.
maxDistance = -inf;
for k = 1 : length(x)
distances = sqrt( (x(k) – x) .^ 2 + (y(k) – y) .^ 2 );
[thisMaxDistance, indexOfMaxDistance] = max(distances);
if thisMaxDistance > maxDistance
maxDistance = thisMaxDistance;
index1 = k;
index2 = indexOfMaxDistance;
end
end
% Find the midpoint of the line.
xMidPoint = mean([x(index1), x(index2)]);
yMidPoint = mean([y(index1), y(index2)]);
longSlope = (y(index1) – y(index2)) / (x(index1) – x(index2))
perpendicularSlope = -1/longSlope
% Use point slope formula (y-ym) = slope * (x – xm) to get points
y1 = perpendicularSlope * (1 – xMidPoint) + yMidPoint;
y2 = perpendicularSlope * (columns – xMidPoint) + yMidPoint;
% Get the profile perpendicular to the midpoint so we can find out when if first enters and last leaves the object.
[cx,cy,c] = improfile(binaryImage,[1, columns], [y1, y2], 1000);
% Get rid of NAN’s that occur when the line’s endpoints go above or below the image.
c(isnan(c)) = 0;
firstIndex = find(c, 1, ‘first’);
lastIndex = find(c, 1, ‘last’);
% Compute the distance of that perpendicular width.
perpendicularWidth = sqrt( (cx(firstIndex) – cx(lastIndex)) .^ 2 + (cy(firstIndex) – cy(lastIndex)) .^ 2 );
% Get the average perpendicular width. This will approximately be the area divided by the longest length.
averageWidth = measurements(blobIndex).Area / maxDistance;
% Plot the boundaries, line, and midpoints over the two images.
% Plot the boundary over the gray scale image
subplot(2, 2, 3);
plot(x, y, ‘y-‘, ‘LineWidth’, 3);
% For this blob, put a line between the points farthest away from each other.
line([x(index1), x(index2)], [y(index1), y(index2)], ‘Color’, ‘r’, ‘LineWidth’, 3);
plot(xMidPoint, yMidPoint, ‘r*’, ‘MarkerSize’, 15, ‘LineWidth’, 2);
% Plot perpendicular line. Make it green across the whole image but magenta inside the blob.
line([1, columns], [y1, y2], ‘Color’, ‘g’, ‘LineWidth’, 3);
line([cx(firstIndex), cx(lastIndex)], [cy(firstIndex), cy(lastIndex)], ‘Color’, ‘m’, ‘LineWidth’, 3);
% Plot the boundary over the binary image
subplot(2, 2, 4);
plot(x, y, ‘y-‘, ‘LineWidth’, 3);
% For this blob, put a line between the points farthest away from each other.
line([x(index1), x(index2)], [y(index1), y(index2)], ‘Color’, ‘r’, ‘LineWidth’, 3);
plot(xMidPoint, yMidPoint, ‘r*’, ‘MarkerSize’, 15, ‘LineWidth’, 2);
% Plot perpendicular line. Make it green across the whole image but magenta inside the blob.
line([1, columns], [y1, y2], ‘Color’, ‘g’, ‘LineWidth’, 3);
line([cx(firstIndex), cx(lastIndex)], [cy(firstIndex), cy(lastIndex)], ‘Color’, ‘m’, ‘LineWidth’, 3);
message = sprintf(‘The longest line is red.nPerpendicular to that, at the midpoint, is green.nMax distance for blob #%d = %.2fnPerpendicular distance at midpoint = %.2fnAverage perpendicular width = %.2f (approximatelynArea = %d’, …
blobIndex, maxDistance, perpendicularWidth, averageWidth, measurements(blobIndex).Area);
fprintf(‘%sn’, message);
uiwait(helpdlg(message));
end
hold off; image processing, crack detection, length, width, regionprops, crack MATLAB Answers — New Questions
How to detect and show the crack in this image and eliminate the rest of the objects (noises)?
I have tried used the morphological structuring element (STREL-line),but there is one problem with my images, the line crack is fixed not only in horizontal and vertical line , it has its degree(0-360), which is this strel-line can’t be used. I used strel-line in order to maintain the line cracks and remove any shapes in the images which is I can’t solve that. I got an idea how to differentiate between the lines and the noises, low gray-level value and high gradient, however this seems not work to this image since the value of gray scale and gradient almost similar to the noises.Can you show me the right way? Attached is the image.I have tried used the morphological structuring element (STREL-line),but there is one problem with my images, the line crack is fixed not only in horizontal and vertical line , it has its degree(0-360), which is this strel-line can’t be used. I used strel-line in order to maintain the line cracks and remove any shapes in the images which is I can’t solve that. I got an idea how to differentiate between the lines and the noises, low gray-level value and high gradient, however this seems not work to this image since the value of gray scale and gradient almost similar to the noises.Can you show me the right way? Attached is the image. I have tried used the morphological structuring element (STREL-line),but there is one problem with my images, the line crack is fixed not only in horizontal and vertical line , it has its degree(0-360), which is this strel-line can’t be used. I used strel-line in order to maintain the line cracks and remove any shapes in the images which is I can’t solve that. I got an idea how to differentiate between the lines and the noises, low gray-level value and high gradient, however this seems not work to this image since the value of gray scale and gradient almost similar to the noises.Can you show me the right way? Attached is the image. image processing, crack detection MATLAB Answers — New Questions
Using sigstrength() for raytracing propagation model
I’m trying to run a ray tracing simulation for a simple ground reflection scenario. I have an STL file with a "floor" that is 1m wide (in y-direction) and 25m long (in the x-direction). I place a transmitter at the location [0.1;0.5;3]. I place 1000 receivers collinear with the transmitter, and at the same height:
clear all;clc;close all;
stlFile = ’25m1m_floor.stl’;
viewer = siteviewer(‘SceneModel’,stlFile); % Required to link STL for ray tracing
tx = txsite(‘cartesian’, ‘AntennaPosition’, [0.1;0.5;3], ‘TransmitterFrequency’, 900e6, ‘TransmitterPower’, 0.001);
numPointsX = 1000;numPointsY = 1;
x = linspace(0.1, 25, numPointsX); y = linspace(0.5, 0.5, numPointsY); [X, Y] = meshgrid(x, y);
Z = 3 * ones(size(X));
for j = 1:numPointsX
for i = 1:numPointsY
rxs(i,j) = rxsite(‘cartesian’, ‘AntennaPosition’, [X(i,j); Y(i,j); Z(i,j)], ‘CoordinateSystem’, ‘cartesian’);
end
end
%To display the tx and rx in siteviewer
%{
show(tx,"ShowAntennaHeight",false);
for i = 1:numel(rxs)
show(rxs(i),"ShowAntennaHeight",false);
end
%}
pm = propagationModel(‘raytracing’, ‘Method’, ‘sbr’, ‘MaxNumReflections’, 1,…
‘SurfaceMaterial’, ‘concrete’, ‘CoordinateSystem’, ‘cartesian’);
ss(1,:) = sigstrength(rxs,tx,pm);
packetLength = 33;
txPower = 0.01;
for j = 1:numPointsX
for i = 1:numPointsY
rx = rxs(i,j);
rays_out = raytrace(tx, rx, pm);
rays = rays_out{:};
[RSS(i,j), rxPower(i,j)] = calcRSSRays(rays,packetLength,txPower);
end
end
figure;plot(x,RSS);
hold;plot(x,ss);
function [RSS,rxPower] = calcRSSRays(rays,packetLength,txPower)
data = randi([0 3], packetLength, 1);
txPacket = sqrt(txPower)*pskmod(data, 4, pi/4);
rxPacket = zeros(1, packetLength);
pathGains = -[rays.PathLoss];
phaseShifts = [rays.PhaseShift];
pathGainsLinear = 10.^(pathGains / 10);
for s = 1:packetLength
E_ray = sqrt(pathGainsLinear) .* exp(-1j .* phaseShifts);
E_total = sum(E_ray * txPacket(s),"all");
rxPacket(s) = E_total;
end
rxPower = mean(abs(rxPacket).^2);
RSS = 10 * log10(rxPower./txPower);
end
The transmitter frequency is 900Mhz so the wavelength is around 0.33m. I’ve specified MaxNumReflections as 1, which I think should capture the ground reflection, and when I plot for one tx-rx pair, I can see that:
Since the tx and rx are all at the same height, I think I should get an RSS profile which decays with distance according to the power rule (i.e. 1/d^2), but with undulations where the ground reflected path interferes constructively and destructively with the line of sight ray.
However, when I plot the output from the sigstrength() function, there are no undulations. I’ve also tried calculating RSS from a packet-level simulation that I wrote, taking the rays output from the raytrace function – I think this is correct, because I do see the interference pattern in it:
Does anyone know if I’ve made a mistake in the ray-tracing/use of sigstrength()? Or is any further calculation required on it?
Or is this something to ask Mathworks support?
NOTE 1: Question editor doesn’t recognize .stl file extension for upload, so I’ve changed the extension to .txt. Extension needs to be changed to .stl to run it.
NOTE 2: I posted this question earlier, but I’ve come up with a better version of the simulation, so I’ve deleted that one before any answers/comments were posted on it.I’m trying to run a ray tracing simulation for a simple ground reflection scenario. I have an STL file with a "floor" that is 1m wide (in y-direction) and 25m long (in the x-direction). I place a transmitter at the location [0.1;0.5;3]. I place 1000 receivers collinear with the transmitter, and at the same height:
clear all;clc;close all;
stlFile = ’25m1m_floor.stl’;
viewer = siteviewer(‘SceneModel’,stlFile); % Required to link STL for ray tracing
tx = txsite(‘cartesian’, ‘AntennaPosition’, [0.1;0.5;3], ‘TransmitterFrequency’, 900e6, ‘TransmitterPower’, 0.001);
numPointsX = 1000;numPointsY = 1;
x = linspace(0.1, 25, numPointsX); y = linspace(0.5, 0.5, numPointsY); [X, Y] = meshgrid(x, y);
Z = 3 * ones(size(X));
for j = 1:numPointsX
for i = 1:numPointsY
rxs(i,j) = rxsite(‘cartesian’, ‘AntennaPosition’, [X(i,j); Y(i,j); Z(i,j)], ‘CoordinateSystem’, ‘cartesian’);
end
end
%To display the tx and rx in siteviewer
%{
show(tx,"ShowAntennaHeight",false);
for i = 1:numel(rxs)
show(rxs(i),"ShowAntennaHeight",false);
end
%}
pm = propagationModel(‘raytracing’, ‘Method’, ‘sbr’, ‘MaxNumReflections’, 1,…
‘SurfaceMaterial’, ‘concrete’, ‘CoordinateSystem’, ‘cartesian’);
ss(1,:) = sigstrength(rxs,tx,pm);
packetLength = 33;
txPower = 0.01;
for j = 1:numPointsX
for i = 1:numPointsY
rx = rxs(i,j);
rays_out = raytrace(tx, rx, pm);
rays = rays_out{:};
[RSS(i,j), rxPower(i,j)] = calcRSSRays(rays,packetLength,txPower);
end
end
figure;plot(x,RSS);
hold;plot(x,ss);
function [RSS,rxPower] = calcRSSRays(rays,packetLength,txPower)
data = randi([0 3], packetLength, 1);
txPacket = sqrt(txPower)*pskmod(data, 4, pi/4);
rxPacket = zeros(1, packetLength);
pathGains = -[rays.PathLoss];
phaseShifts = [rays.PhaseShift];
pathGainsLinear = 10.^(pathGains / 10);
for s = 1:packetLength
E_ray = sqrt(pathGainsLinear) .* exp(-1j .* phaseShifts);
E_total = sum(E_ray * txPacket(s),"all");
rxPacket(s) = E_total;
end
rxPower = mean(abs(rxPacket).^2);
RSS = 10 * log10(rxPower./txPower);
end
The transmitter frequency is 900Mhz so the wavelength is around 0.33m. I’ve specified MaxNumReflections as 1, which I think should capture the ground reflection, and when I plot for one tx-rx pair, I can see that:
Since the tx and rx are all at the same height, I think I should get an RSS profile which decays with distance according to the power rule (i.e. 1/d^2), but with undulations where the ground reflected path interferes constructively and destructively with the line of sight ray.
However, when I plot the output from the sigstrength() function, there are no undulations. I’ve also tried calculating RSS from a packet-level simulation that I wrote, taking the rays output from the raytrace function – I think this is correct, because I do see the interference pattern in it:
Does anyone know if I’ve made a mistake in the ray-tracing/use of sigstrength()? Or is any further calculation required on it?
Or is this something to ask Mathworks support?
NOTE 1: Question editor doesn’t recognize .stl file extension for upload, so I’ve changed the extension to .txt. Extension needs to be changed to .stl to run it.
NOTE 2: I posted this question earlier, but I’ve come up with a better version of the simulation, so I’ve deleted that one before any answers/comments were posted on it. I’m trying to run a ray tracing simulation for a simple ground reflection scenario. I have an STL file with a "floor" that is 1m wide (in y-direction) and 25m long (in the x-direction). I place a transmitter at the location [0.1;0.5;3]. I place 1000 receivers collinear with the transmitter, and at the same height:
clear all;clc;close all;
stlFile = ’25m1m_floor.stl’;
viewer = siteviewer(‘SceneModel’,stlFile); % Required to link STL for ray tracing
tx = txsite(‘cartesian’, ‘AntennaPosition’, [0.1;0.5;3], ‘TransmitterFrequency’, 900e6, ‘TransmitterPower’, 0.001);
numPointsX = 1000;numPointsY = 1;
x = linspace(0.1, 25, numPointsX); y = linspace(0.5, 0.5, numPointsY); [X, Y] = meshgrid(x, y);
Z = 3 * ones(size(X));
for j = 1:numPointsX
for i = 1:numPointsY
rxs(i,j) = rxsite(‘cartesian’, ‘AntennaPosition’, [X(i,j); Y(i,j); Z(i,j)], ‘CoordinateSystem’, ‘cartesian’);
end
end
%To display the tx and rx in siteviewer
%{
show(tx,"ShowAntennaHeight",false);
for i = 1:numel(rxs)
show(rxs(i),"ShowAntennaHeight",false);
end
%}
pm = propagationModel(‘raytracing’, ‘Method’, ‘sbr’, ‘MaxNumReflections’, 1,…
‘SurfaceMaterial’, ‘concrete’, ‘CoordinateSystem’, ‘cartesian’);
ss(1,:) = sigstrength(rxs,tx,pm);
packetLength = 33;
txPower = 0.01;
for j = 1:numPointsX
for i = 1:numPointsY
rx = rxs(i,j);
rays_out = raytrace(tx, rx, pm);
rays = rays_out{:};
[RSS(i,j), rxPower(i,j)] = calcRSSRays(rays,packetLength,txPower);
end
end
figure;plot(x,RSS);
hold;plot(x,ss);
function [RSS,rxPower] = calcRSSRays(rays,packetLength,txPower)
data = randi([0 3], packetLength, 1);
txPacket = sqrt(txPower)*pskmod(data, 4, pi/4);
rxPacket = zeros(1, packetLength);
pathGains = -[rays.PathLoss];
phaseShifts = [rays.PhaseShift];
pathGainsLinear = 10.^(pathGains / 10);
for s = 1:packetLength
E_ray = sqrt(pathGainsLinear) .* exp(-1j .* phaseShifts);
E_total = sum(E_ray * txPacket(s),"all");
rxPacket(s) = E_total;
end
rxPower = mean(abs(rxPacket).^2);
RSS = 10 * log10(rxPower./txPower);
end
The transmitter frequency is 900Mhz so the wavelength is around 0.33m. I’ve specified MaxNumReflections as 1, which I think should capture the ground reflection, and when I plot for one tx-rx pair, I can see that:
Since the tx and rx are all at the same height, I think I should get an RSS profile which decays with distance according to the power rule (i.e. 1/d^2), but with undulations where the ground reflected path interferes constructively and destructively with the line of sight ray.
However, when I plot the output from the sigstrength() function, there are no undulations. I’ve also tried calculating RSS from a packet-level simulation that I wrote, taking the rays output from the raytrace function – I think this is correct, because I do see the interference pattern in it:
Does anyone know if I’ve made a mistake in the ray-tracing/use of sigstrength()? Or is any further calculation required on it?
Or is this something to ask Mathworks support?
NOTE 1: Question editor doesn’t recognize .stl file extension for upload, so I’ve changed the extension to .txt. Extension needs to be changed to .stl to run it.
NOTE 2: I posted this question earlier, but I’ve come up with a better version of the simulation, so I’ve deleted that one before any answers/comments were posted on it. ray tracing, signal processing, communication, simulation MATLAB Answers — New Questions
Simplifying a TDMS reading code
I am trying to read multiple groups and channels of a TDMS file and doing some graphing and calculations at the end. I need to be able to acceses any channel or group that I want to use in the graphs or calcualtions, I would really apperciate it if someone had any advice on sliming the code down it currently takes 6 mins to run which is a really long time.
defaultFolder = ‘C:UserslillypColostateLute,Chris – EM-TRAS internalMatlab’;
addpath(defaultFolder);
fileFilter = ‘*.tdms’;
[fileName, filepath] = uigetfile(fullfile(defaultFolder, fileFilter), ‘Select a TDMS file’);
if fileName ~= 0
fullFilePath = fullfile(filepath, fileName);
disp([‘Selected file: ‘, fullFilePath]);
else
disp(‘No file selected.’);
end
fileName = fullFilePath;
group_Time = "Torques";
channel_Time = "Timestamp";
tdmsreadprop(fileName, "ChannelGroupName",group_Time, "ChannelName", channel_Time);
data = tdmsread(fileName, "ChannelGroupName",group_Time, "ChannelName", channel_Time);
time = data{1};
if istable(time)
time = table2array(time);
elseif isdatetime(time)
time = seconds(time – time(1));
end
% Speed readings%
group_N1 = "Rotary encoders";
channel_N1 = "N1 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N1, "ChannelName", channel_N1);
data = tdmsread(fileName, "ChannelGroupName",group_N1, "ChannelName", channel_N1);
N1 = data{1};
group_N2 = "Rotary encoders";
channel_N2 = "N2 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N2, "ChannelName", channel_N2);
data = tdmsread(fileName, "ChannelGroupName",group_N2, "ChannelName", channel_N2);
N2 = data{1};
group_N3 = "Rotary encoders";
channel_N3 = "N3 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N3, "ChannelName", channel_N3);
data = tdmsread(fileName, "ChannelGroupName",group_N3, "ChannelName", channel_N3);
N3 = data{1};
group_N4 = "Rotary encoders";
channel_N4 = "N4 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N4, "ChannelName", channel_N4);
data = tdmsread(fileName, "ChannelGroupName",group_N4, "ChannelName", channel_N4);
N4 = data{1};
group_N5 = "Rotary encoders";
channel_N5 = "N5 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N5, "ChannelName", channel_N5);
data = tdmsread(fileName, "ChannelGroupName",group_N5, "ChannelName", channel_N5);
N5 = data{1};
group_N6 = "Rotary encoders";
channel_N6 = "N6 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N6, "ChannelName", channel_N6);
data = tdmsread(fileName, "ChannelGroupName",group_N6, "ChannelName", channel_N6);
N6 = data{1};
group_N7 = "Rotary encoders";
channel_N7 = "N7 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N7, "ChannelName", channel_N7);
data = tdmsread(fileName, "ChannelGroupName",group_N7, "ChannelName", channel_N7);
N7 = data{1};
group_N8 = "Rotary encoders";
channel_N8 = "N8 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N8, "ChannelName", channel_N8);
data = tdmsread(fileName, "ChannelGroupName",group_N8, "ChannelName", channel_N8);
N8 = data{1};
% Torque readings%
group_T1 = "Torques";
channel_T1 = "T1 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T1, "ChannelName", channel_T1);
data = tdmsread(fileName, "ChannelGroupName",group_T1, "ChannelName", channel_T1);
T1 = data{1};
group_T2 = "Torques";
channel_T2 = "T2 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T2, "ChannelName", channel_T2);
data = tdmsread(fileName, "ChannelGroupName",group_T2, "ChannelName", channel_T2);
T2 = data{1};
group_T3 = "Torques";
channel_T3 = "T3 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T3, "ChannelName", channel_T3);
data = tdmsread(fileName, "ChannelGroupName",group_T3, "ChannelName", channel_T3);
T3 = data{1};
group_T4 = "Torques";
channel_T4 = "T4 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T4, "ChannelName", channel_T4);
data = tdmsread(fileName, "ChannelGroupName",group_T4, "ChannelName", channel_T4);
T4 = data{1};
group_T5 = "Torques";
channel_T5 = "T5 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T5, "ChannelName", channel_T5);
data = tdmsread(fileName, "ChannelGroupName",group_T5, "ChannelName", channel_T5);
T5 = data{1};
group_T6 = "Torques";
channel_T6 = "T6 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T6, "ChannelName", channel_T6);
data = tdmsread(fileName, "ChannelGroupName",group_T6, "ChannelName", channel_T6);
T6 = data{1};
group_T7 = "Torques";
channel_T7 = "T7 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T7, "ChannelName", channel_T7);
data = tdmsread(fileName, "ChannelGroupName",group_T7, "ChannelName", channel_T7);
T7 = data{1};
group_T8 = "Torques";
channel_T8 = "T8 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T8, "ChannelName", channel_T8);
data = tdmsread(fileName, "ChannelGroupName",group_T8, "ChannelName", channel_T8);
T8 = data{1};
%Current readings%
group_I1a = "Motor voltages and currents";
channel_I1a = "I1a [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I1a, "ChannelName", channel_I1a);
data = tdmsread(fileName, "ChannelGroupName",group_I1a, "ChannelName", channel_I1a);
I1a = data{1};
group_I1b = "Motor voltages and currents";
channel_I1b = "I1b [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I1b, "ChannelName", channel_I1b);
data = tdmsread(fileName, "ChannelGroupName",group_I1b, "ChannelName", channel_I1b);
I1b = data{1};
group_I1c = "Motor voltages and currents";
channel_I1c = "I1c [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I1c, "ChannelName", channel_I1c);
data = tdmsread(fileName, "ChannelGroupName",group_I1c, "ChannelName", channel_I1c);
I1c = data{1};
group_I2a = "Motor voltages and currents";
channel_I2a = "I2a [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I2a, "ChannelName", channel_I2a);
data = tdmsread(fileName, "ChannelGroupName",group_I2a, "ChannelName", channel_I2a);
I2a = data{1};
group_I2b = "Motor voltages and currents";
channel_I2b = "I2b [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I2b, "ChannelName", channel_I2b);
data = tdmsread(fileName, "ChannelGroupName",group_I2b, "ChannelName", channel_I2b);
I2b = data{1};
group_I2c = "Motor voltages and currents";
channel_I2c = "I2c [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I2c, "ChannelName", channel_I2c);
data = tdmsread(fileName, "ChannelGroupName",group_I2c, "ChannelName", channel_I2c);
I2c = data{1};
group_I3a = "Motor voltages and currents";
channel_I3a = "I3a [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I3a, "ChannelName", channel_I3a);
data = tdmsread(fileName, "ChannelGroupName",group_I3a, "ChannelName", channel_I3a);
I3a = data{1};
group_I3b = "Motor voltages and currents";
channel_I3b = "I3b [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I3b, "ChannelName", channel_I3b);
data = tdmsread(fileName, "ChannelGroupName",group_I3b, "ChannelName", channel_I3b);
I3b = data{1};
group_I3c = "Motor voltages and currents";
channel_I3c = "I3c [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I3c, "ChannelName", channel_I3c);
data = tdmsread(fileName, "ChannelGroupName",group_I3c, "ChannelName", channel_I3c);
I3c = data{1};
group_I4a = "Motor voltages and currents";
channel_I4a = "I4a [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I4a, "ChannelName", channel_I4a);
data = tdmsread(fileName, "ChannelGroupName",group_I4a, "ChannelName", channel_I4a);
I4a = data{1};
group_I4b = "Motor voltages and currents";
channel_I4b = "I4b [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I4b, "ChannelName", channel_I4b);
data = tdmsread(fileName, "ChannelGroupName",group_I4b, "ChannelName", channel_I4b);
I4b = data{1};
group_I4c = "Motor voltages and currents";
channel_I4c = "I4c [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I4c, "ChannelName", channel_I4c);
data = tdmsread(fileName, "ChannelGroupName",group_I4c, "ChannelName", channel_I4c);
I4c = data{1};
group_IDC = "Motor voltages and currents";
channel_IDC = "IDC [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_IDC, "ChannelName", channel_IDC);
data = tdmsread(fileName, "ChannelGroupName",group_IDC, "ChannelName", channel_IDC);
IDC = data{1};
%Voltage readings%
group_V1ab = "Motor voltages and currents";
channel_V1ab = "V1ab [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V1ab, "ChannelName", channel_V1ab);
data = tdmsread(fileName, "ChannelGroupName",group_V1ab, "ChannelName", channel_V1ab);
V1ab = data{1};
group_V1bc = "Motor voltages and currents";
channel_V1bc = "V1bc [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V1bc, "ChannelName", channel_V1bc);
data = tdmsread(fileName, "ChannelGroupName",group_V1bc, "ChannelName", channel_V1bc);
V1bc = data{1};
group_V1ca = "Motor voltages and currents";
channel_V1ca = "V1ca [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V1ca, "ChannelName", channel_V1ca);
data = tdmsread(fileName, "ChannelGroupName",group_V1ca, "ChannelName", channel_V1ca);
V1ca = data{1};
group_V2ab = "Motor voltages and currents";
channel_V2ab = "V2ab [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V2ab, "ChannelName", channel_V2ab);
data = tdmsread(fileName, "ChannelGroupName",group_V2ab, "ChannelName", channel_V2ab);
V2ab = data{1};
group_V2bc = "Motor voltages and currents";
channel_V2bc = "V2bc [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V2bc, "ChannelName", channel_V2bc);
data = tdmsread(fileName, "ChannelGroupName",group_V2bc, "ChannelName", channel_V2bc);
V2bc = data{1};
group_V2ca = "Motor voltages and currents";
channel_V2ca = "V2ca [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V2ca, "ChannelName", channel_V2ca);
data = tdmsread(fileName, "ChannelGroupName",group_V2ca, "ChannelName", channel_V2ca);
V2ca = data{1};
group_V3ab = "Motor voltages and currents";
channel_V3ab = "V3ab [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V3ab, "ChannelName", channel_V3ab);
data = tdmsread(fileName, "ChannelGroupName",group_V3ab, "ChannelName", channel_V3ab);
V3ab = data{1};
group_V3bc = "Motor voltages and currents";
channel_V3bc = "V3bc [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V3bc, "ChannelName", channel_V3bc);
data = tdmsread(fileName, "ChannelGroupName",group_V3bc, "ChannelName", channel_V3bc);
V3bc = data{1};
group_V3ca = "Motor voltages and currents";
channel_V3ca = "V3ca [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V3ca, "ChannelName", channel_V3ca);
data = tdmsread(fileName, "ChannelGroupName",group_V3ca, "ChannelName", channel_V3ca);
V3ca = data{1};
group_V4ab = "Motor voltages and currents";
channel_V4ab = "V4ab [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V4ab, "ChannelName", channel_V4ab);
data = tdmsread(fileName, "ChannelGroupName",group_V4ab, "ChannelName", channel_V4ab);
V4ab = data{1};
group_V4bc = "Motor voltages and currents";
channel_V4bc = "V4bc [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V4bc, "ChannelName", channel_V4bc);
data = tdmsread(fileName, "ChannelGroupName",group_V4bc, "ChannelName", channel_V4bc);
V4bc = data{1};
group_V4ca = "Motor voltages and currents";
channel_V4ca = "V4ca [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V4ca, "ChannelName", channel_V4ca);
data = tdmsread(fileName, "ChannelGroupName",group_V4ca, "ChannelName", channel_V4ca);
V4ca = data{1};
group_VDC = "Motor voltages and currents";
channel_VDC = "VDC [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_VDC, "ChannelName", channel_VDC);
data = tdmsread(fileName, "ChannelGroupName",group_VDC, "ChannelName", channel_VDC);
VDC = data{1};
% Control Commands- Speed
group_M5S = "Control commands";
channel_M5S = "M5 speed cmd [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_M5S, "ChannelName", channel_M5S);
data = tdmsread(fileName, "ChannelGroupName",group_M5S, "ChannelName", channel_M5S);
M5S = data{1};
group_M6S = "Control commands";
channel_M6S = "M6 speed cmd [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_M6S, "ChannelName", channel_M6S);
data = tdmsread(fileName, "ChannelGroupName",group_M6S, "ChannelName", channel_M6S);
M6S = data{1};
group_M7S = "Control commands";
channel_M7S = "M7 speed cmd [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_M7S, "ChannelName", channel_M7S);
data = tdmsread(fileName, "ChannelGroupName",group_M7S, "ChannelName", channel_M7S);
M7S = data{1};
group_M8S = "Control commands";
channel_M8S = "M8 speed cmd [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_M8S, "ChannelName", channel_M8S);
data = tdmsread(fileName, "ChannelGroupName",group_M8S, "ChannelName", channel_M8S);
M8S = data{1};
% Control Commands- Torque
group_M5T = "Control commands";
channel_M5T = "M5 torque cmd [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_M5T, "ChannelName", channel_M5T);
data = tdmsread(fileName, "ChannelGroupName",group_M5T, "ChannelName", channel_M5T);
M5T = data{1};
group_M6T = "Control commands";
channel_M6T = "M6 torque cmd [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_M6T, "ChannelName", channel_M6T);
data = tdmsread(fileName, "ChannelGroupName",group_M6T, "ChannelName", channel_M6T);
M6T = data{1};
group_M7T = "Control commands";
channel_M7T = "M7 torque cmd [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_M7T, "ChannelName", channel_M7T);
data = tdmsread(fileName, "ChannelGroupName",group_M7T, "ChannelName", channel_M7T);
M7T = data{1};
group_M8T = "Control commands";
channel_M8T = "M8 torque cmd [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_M8T, "ChannelName", channel_M8T);
data = tdmsread(fileName, "ChannelGroupName",group_M8T, "ChannelName", channel_M8T);
M8T = data{1};
%ARRAYS
N1 = table2array(N1);
N2 = table2array(N2);
N3 = table2array(N3);
N4 = table2array(N4);
N5 = table2array(N5);
N6 = table2array(N6);
N7 = table2array(N7);
N8 = table2array(N8);
T1 = table2array(T1);
T2 = table2array(T2);
T3 = table2array(T3);
T4 = table2array(T4);
T5 = table2array(T5);
T6 = table2array(T6);
T7 = table2array(T7);
T8 = table2array(T8);
I1a = table2array(I1a);
I2a = table2array(I2a);
I3a = table2array(I3a);
I4a = table2array(I4a);
I1b = table2array(I1b);
I2b = table2array(I2b);
I3b = table2array(I3b);
I4b = table2array(I4b);
I1c = table2array(I1c);
I2c = table2array(I2c);
I3c = table2array(I3c);
I4c = table2array(I4c);
IDC = table2array(IDC);
V1ab = table2array(V1ab);
V2ab = table2array(V2ab);
V3ab = table2array(V3ab);
V4ab = table2array(V4ab);
V1bc = table2array(V1bc);
V2bc = table2array(V2bc);
V3bc = table2array(V3bc);
V4bc = table2array(V4bc);
V1ca = table2array(V1ca);
V2ca = table2array(V2ca);
V3ca = table2array(V3ca);
V4ca = table2array(V4ca);
VDC= table2array(VDC);
M5S = table2array(M5S);
M6S = table2array(M6S);
M7S = table2array(M7S);
M8S = table2array(M8S);
M5T = table2array(M5T);
M6T = table2array(M6T);
M7T = table2array(M7T);
M8T = table2array(M8T);
% GRAPHS AND TIME STAMPS
minLength_1 = min([length(time), length(T1), length(I1a)]);
minLength_2 = min([length(time), length(T1), length(M5T)]);
time = time(1:minLength_1);
T5 = T5(1:minLength_1);
I1a = I1a(1:minLength_1);
M5T = M5T(1:minLength_2);
figure;
hold on;
subplot(2, 1, 1);
plot(time, T5, ‘r-‘, ‘DisplayName’, ‘T5 [Nm]’);
xlabel(‘Time (s)’);
ylabel(‘T5 [Nm]’);
title(‘T5 vs. Time’);
legend(‘show’);
subplot(2, 1, 2);
plot(time, M5T, ‘b-‘, ‘DisplayName’, ‘M5T [Nm]’);
xlabel(‘Time (s)’);
ylabel(‘M5T [Nm]’);
title(‘M5T vs. Time’);
legend(‘show’);
legend;
hold off;
[~, maxIdx] = max(T5);
maxTime = time(maxIdx);
zeroCrossIdx = find(T5(maxIdx:end) <= 0, 1, ‘first’) + maxIdx – 1;
if isempty(zeroCrossIdx)
timeToZero = NaN;
disp(‘Data does not return to zero after maximum.’);
else
timeToZero = time(zeroCrossIdx) – maxTime;
disp(timeToZero);
end
% Find the index where interpolated T5 matches M5
matchIndex = find(T5 == M5T);
if isempty(matchIndex)
disp(‘T5 does not match M5 ‘);
else
matchTime = commonTime(matchIndex);
fprintf(‘T5 matches M5 at t = %.2f seconds (interpolated).n’, matchTime);
endI am trying to read multiple groups and channels of a TDMS file and doing some graphing and calculations at the end. I need to be able to acceses any channel or group that I want to use in the graphs or calcualtions, I would really apperciate it if someone had any advice on sliming the code down it currently takes 6 mins to run which is a really long time.
defaultFolder = ‘C:UserslillypColostateLute,Chris – EM-TRAS internalMatlab’;
addpath(defaultFolder);
fileFilter = ‘*.tdms’;
[fileName, filepath] = uigetfile(fullfile(defaultFolder, fileFilter), ‘Select a TDMS file’);
if fileName ~= 0
fullFilePath = fullfile(filepath, fileName);
disp([‘Selected file: ‘, fullFilePath]);
else
disp(‘No file selected.’);
end
fileName = fullFilePath;
group_Time = "Torques";
channel_Time = "Timestamp";
tdmsreadprop(fileName, "ChannelGroupName",group_Time, "ChannelName", channel_Time);
data = tdmsread(fileName, "ChannelGroupName",group_Time, "ChannelName", channel_Time);
time = data{1};
if istable(time)
time = table2array(time);
elseif isdatetime(time)
time = seconds(time – time(1));
end
% Speed readings%
group_N1 = "Rotary encoders";
channel_N1 = "N1 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N1, "ChannelName", channel_N1);
data = tdmsread(fileName, "ChannelGroupName",group_N1, "ChannelName", channel_N1);
N1 = data{1};
group_N2 = "Rotary encoders";
channel_N2 = "N2 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N2, "ChannelName", channel_N2);
data = tdmsread(fileName, "ChannelGroupName",group_N2, "ChannelName", channel_N2);
N2 = data{1};
group_N3 = "Rotary encoders";
channel_N3 = "N3 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N3, "ChannelName", channel_N3);
data = tdmsread(fileName, "ChannelGroupName",group_N3, "ChannelName", channel_N3);
N3 = data{1};
group_N4 = "Rotary encoders";
channel_N4 = "N4 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N4, "ChannelName", channel_N4);
data = tdmsread(fileName, "ChannelGroupName",group_N4, "ChannelName", channel_N4);
N4 = data{1};
group_N5 = "Rotary encoders";
channel_N5 = "N5 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N5, "ChannelName", channel_N5);
data = tdmsread(fileName, "ChannelGroupName",group_N5, "ChannelName", channel_N5);
N5 = data{1};
group_N6 = "Rotary encoders";
channel_N6 = "N6 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N6, "ChannelName", channel_N6);
data = tdmsread(fileName, "ChannelGroupName",group_N6, "ChannelName", channel_N6);
N6 = data{1};
group_N7 = "Rotary encoders";
channel_N7 = "N7 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N7, "ChannelName", channel_N7);
data = tdmsread(fileName, "ChannelGroupName",group_N7, "ChannelName", channel_N7);
N7 = data{1};
group_N8 = "Rotary encoders";
channel_N8 = "N8 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N8, "ChannelName", channel_N8);
data = tdmsread(fileName, "ChannelGroupName",group_N8, "ChannelName", channel_N8);
N8 = data{1};
% Torque readings%
group_T1 = "Torques";
channel_T1 = "T1 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T1, "ChannelName", channel_T1);
data = tdmsread(fileName, "ChannelGroupName",group_T1, "ChannelName", channel_T1);
T1 = data{1};
group_T2 = "Torques";
channel_T2 = "T2 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T2, "ChannelName", channel_T2);
data = tdmsread(fileName, "ChannelGroupName",group_T2, "ChannelName", channel_T2);
T2 = data{1};
group_T3 = "Torques";
channel_T3 = "T3 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T3, "ChannelName", channel_T3);
data = tdmsread(fileName, "ChannelGroupName",group_T3, "ChannelName", channel_T3);
T3 = data{1};
group_T4 = "Torques";
channel_T4 = "T4 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T4, "ChannelName", channel_T4);
data = tdmsread(fileName, "ChannelGroupName",group_T4, "ChannelName", channel_T4);
T4 = data{1};
group_T5 = "Torques";
channel_T5 = "T5 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T5, "ChannelName", channel_T5);
data = tdmsread(fileName, "ChannelGroupName",group_T5, "ChannelName", channel_T5);
T5 = data{1};
group_T6 = "Torques";
channel_T6 = "T6 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T6, "ChannelName", channel_T6);
data = tdmsread(fileName, "ChannelGroupName",group_T6, "ChannelName", channel_T6);
T6 = data{1};
group_T7 = "Torques";
channel_T7 = "T7 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T7, "ChannelName", channel_T7);
data = tdmsread(fileName, "ChannelGroupName",group_T7, "ChannelName", channel_T7);
T7 = data{1};
group_T8 = "Torques";
channel_T8 = "T8 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T8, "ChannelName", channel_T8);
data = tdmsread(fileName, "ChannelGroupName",group_T8, "ChannelName", channel_T8);
T8 = data{1};
%Current readings%
group_I1a = "Motor voltages and currents";
channel_I1a = "I1a [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I1a, "ChannelName", channel_I1a);
data = tdmsread(fileName, "ChannelGroupName",group_I1a, "ChannelName", channel_I1a);
I1a = data{1};
group_I1b = "Motor voltages and currents";
channel_I1b = "I1b [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I1b, "ChannelName", channel_I1b);
data = tdmsread(fileName, "ChannelGroupName",group_I1b, "ChannelName", channel_I1b);
I1b = data{1};
group_I1c = "Motor voltages and currents";
channel_I1c = "I1c [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I1c, "ChannelName", channel_I1c);
data = tdmsread(fileName, "ChannelGroupName",group_I1c, "ChannelName", channel_I1c);
I1c = data{1};
group_I2a = "Motor voltages and currents";
channel_I2a = "I2a [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I2a, "ChannelName", channel_I2a);
data = tdmsread(fileName, "ChannelGroupName",group_I2a, "ChannelName", channel_I2a);
I2a = data{1};
group_I2b = "Motor voltages and currents";
channel_I2b = "I2b [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I2b, "ChannelName", channel_I2b);
data = tdmsread(fileName, "ChannelGroupName",group_I2b, "ChannelName", channel_I2b);
I2b = data{1};
group_I2c = "Motor voltages and currents";
channel_I2c = "I2c [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I2c, "ChannelName", channel_I2c);
data = tdmsread(fileName, "ChannelGroupName",group_I2c, "ChannelName", channel_I2c);
I2c = data{1};
group_I3a = "Motor voltages and currents";
channel_I3a = "I3a [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I3a, "ChannelName", channel_I3a);
data = tdmsread(fileName, "ChannelGroupName",group_I3a, "ChannelName", channel_I3a);
I3a = data{1};
group_I3b = "Motor voltages and currents";
channel_I3b = "I3b [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I3b, "ChannelName", channel_I3b);
data = tdmsread(fileName, "ChannelGroupName",group_I3b, "ChannelName", channel_I3b);
I3b = data{1};
group_I3c = "Motor voltages and currents";
channel_I3c = "I3c [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I3c, "ChannelName", channel_I3c);
data = tdmsread(fileName, "ChannelGroupName",group_I3c, "ChannelName", channel_I3c);
I3c = data{1};
group_I4a = "Motor voltages and currents";
channel_I4a = "I4a [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I4a, "ChannelName", channel_I4a);
data = tdmsread(fileName, "ChannelGroupName",group_I4a, "ChannelName", channel_I4a);
I4a = data{1};
group_I4b = "Motor voltages and currents";
channel_I4b = "I4b [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I4b, "ChannelName", channel_I4b);
data = tdmsread(fileName, "ChannelGroupName",group_I4b, "ChannelName", channel_I4b);
I4b = data{1};
group_I4c = "Motor voltages and currents";
channel_I4c = "I4c [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I4c, "ChannelName", channel_I4c);
data = tdmsread(fileName, "ChannelGroupName",group_I4c, "ChannelName", channel_I4c);
I4c = data{1};
group_IDC = "Motor voltages and currents";
channel_IDC = "IDC [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_IDC, "ChannelName", channel_IDC);
data = tdmsread(fileName, "ChannelGroupName",group_IDC, "ChannelName", channel_IDC);
IDC = data{1};
%Voltage readings%
group_V1ab = "Motor voltages and currents";
channel_V1ab = "V1ab [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V1ab, "ChannelName", channel_V1ab);
data = tdmsread(fileName, "ChannelGroupName",group_V1ab, "ChannelName", channel_V1ab);
V1ab = data{1};
group_V1bc = "Motor voltages and currents";
channel_V1bc = "V1bc [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V1bc, "ChannelName", channel_V1bc);
data = tdmsread(fileName, "ChannelGroupName",group_V1bc, "ChannelName", channel_V1bc);
V1bc = data{1};
group_V1ca = "Motor voltages and currents";
channel_V1ca = "V1ca [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V1ca, "ChannelName", channel_V1ca);
data = tdmsread(fileName, "ChannelGroupName",group_V1ca, "ChannelName", channel_V1ca);
V1ca = data{1};
group_V2ab = "Motor voltages and currents";
channel_V2ab = "V2ab [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V2ab, "ChannelName", channel_V2ab);
data = tdmsread(fileName, "ChannelGroupName",group_V2ab, "ChannelName", channel_V2ab);
V2ab = data{1};
group_V2bc = "Motor voltages and currents";
channel_V2bc = "V2bc [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V2bc, "ChannelName", channel_V2bc);
data = tdmsread(fileName, "ChannelGroupName",group_V2bc, "ChannelName", channel_V2bc);
V2bc = data{1};
group_V2ca = "Motor voltages and currents";
channel_V2ca = "V2ca [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V2ca, "ChannelName", channel_V2ca);
data = tdmsread(fileName, "ChannelGroupName",group_V2ca, "ChannelName", channel_V2ca);
V2ca = data{1};
group_V3ab = "Motor voltages and currents";
channel_V3ab = "V3ab [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V3ab, "ChannelName", channel_V3ab);
data = tdmsread(fileName, "ChannelGroupName",group_V3ab, "ChannelName", channel_V3ab);
V3ab = data{1};
group_V3bc = "Motor voltages and currents";
channel_V3bc = "V3bc [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V3bc, "ChannelName", channel_V3bc);
data = tdmsread(fileName, "ChannelGroupName",group_V3bc, "ChannelName", channel_V3bc);
V3bc = data{1};
group_V3ca = "Motor voltages and currents";
channel_V3ca = "V3ca [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V3ca, "ChannelName", channel_V3ca);
data = tdmsread(fileName, "ChannelGroupName",group_V3ca, "ChannelName", channel_V3ca);
V3ca = data{1};
group_V4ab = "Motor voltages and currents";
channel_V4ab = "V4ab [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V4ab, "ChannelName", channel_V4ab);
data = tdmsread(fileName, "ChannelGroupName",group_V4ab, "ChannelName", channel_V4ab);
V4ab = data{1};
group_V4bc = "Motor voltages and currents";
channel_V4bc = "V4bc [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V4bc, "ChannelName", channel_V4bc);
data = tdmsread(fileName, "ChannelGroupName",group_V4bc, "ChannelName", channel_V4bc);
V4bc = data{1};
group_V4ca = "Motor voltages and currents";
channel_V4ca = "V4ca [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V4ca, "ChannelName", channel_V4ca);
data = tdmsread(fileName, "ChannelGroupName",group_V4ca, "ChannelName", channel_V4ca);
V4ca = data{1};
group_VDC = "Motor voltages and currents";
channel_VDC = "VDC [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_VDC, "ChannelName", channel_VDC);
data = tdmsread(fileName, "ChannelGroupName",group_VDC, "ChannelName", channel_VDC);
VDC = data{1};
% Control Commands- Speed
group_M5S = "Control commands";
channel_M5S = "M5 speed cmd [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_M5S, "ChannelName", channel_M5S);
data = tdmsread(fileName, "ChannelGroupName",group_M5S, "ChannelName", channel_M5S);
M5S = data{1};
group_M6S = "Control commands";
channel_M6S = "M6 speed cmd [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_M6S, "ChannelName", channel_M6S);
data = tdmsread(fileName, "ChannelGroupName",group_M6S, "ChannelName", channel_M6S);
M6S = data{1};
group_M7S = "Control commands";
channel_M7S = "M7 speed cmd [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_M7S, "ChannelName", channel_M7S);
data = tdmsread(fileName, "ChannelGroupName",group_M7S, "ChannelName", channel_M7S);
M7S = data{1};
group_M8S = "Control commands";
channel_M8S = "M8 speed cmd [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_M8S, "ChannelName", channel_M8S);
data = tdmsread(fileName, "ChannelGroupName",group_M8S, "ChannelName", channel_M8S);
M8S = data{1};
% Control Commands- Torque
group_M5T = "Control commands";
channel_M5T = "M5 torque cmd [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_M5T, "ChannelName", channel_M5T);
data = tdmsread(fileName, "ChannelGroupName",group_M5T, "ChannelName", channel_M5T);
M5T = data{1};
group_M6T = "Control commands";
channel_M6T = "M6 torque cmd [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_M6T, "ChannelName", channel_M6T);
data = tdmsread(fileName, "ChannelGroupName",group_M6T, "ChannelName", channel_M6T);
M6T = data{1};
group_M7T = "Control commands";
channel_M7T = "M7 torque cmd [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_M7T, "ChannelName", channel_M7T);
data = tdmsread(fileName, "ChannelGroupName",group_M7T, "ChannelName", channel_M7T);
M7T = data{1};
group_M8T = "Control commands";
channel_M8T = "M8 torque cmd [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_M8T, "ChannelName", channel_M8T);
data = tdmsread(fileName, "ChannelGroupName",group_M8T, "ChannelName", channel_M8T);
M8T = data{1};
%ARRAYS
N1 = table2array(N1);
N2 = table2array(N2);
N3 = table2array(N3);
N4 = table2array(N4);
N5 = table2array(N5);
N6 = table2array(N6);
N7 = table2array(N7);
N8 = table2array(N8);
T1 = table2array(T1);
T2 = table2array(T2);
T3 = table2array(T3);
T4 = table2array(T4);
T5 = table2array(T5);
T6 = table2array(T6);
T7 = table2array(T7);
T8 = table2array(T8);
I1a = table2array(I1a);
I2a = table2array(I2a);
I3a = table2array(I3a);
I4a = table2array(I4a);
I1b = table2array(I1b);
I2b = table2array(I2b);
I3b = table2array(I3b);
I4b = table2array(I4b);
I1c = table2array(I1c);
I2c = table2array(I2c);
I3c = table2array(I3c);
I4c = table2array(I4c);
IDC = table2array(IDC);
V1ab = table2array(V1ab);
V2ab = table2array(V2ab);
V3ab = table2array(V3ab);
V4ab = table2array(V4ab);
V1bc = table2array(V1bc);
V2bc = table2array(V2bc);
V3bc = table2array(V3bc);
V4bc = table2array(V4bc);
V1ca = table2array(V1ca);
V2ca = table2array(V2ca);
V3ca = table2array(V3ca);
V4ca = table2array(V4ca);
VDC= table2array(VDC);
M5S = table2array(M5S);
M6S = table2array(M6S);
M7S = table2array(M7S);
M8S = table2array(M8S);
M5T = table2array(M5T);
M6T = table2array(M6T);
M7T = table2array(M7T);
M8T = table2array(M8T);
% GRAPHS AND TIME STAMPS
minLength_1 = min([length(time), length(T1), length(I1a)]);
minLength_2 = min([length(time), length(T1), length(M5T)]);
time = time(1:minLength_1);
T5 = T5(1:minLength_1);
I1a = I1a(1:minLength_1);
M5T = M5T(1:minLength_2);
figure;
hold on;
subplot(2, 1, 1);
plot(time, T5, ‘r-‘, ‘DisplayName’, ‘T5 [Nm]’);
xlabel(‘Time (s)’);
ylabel(‘T5 [Nm]’);
title(‘T5 vs. Time’);
legend(‘show’);
subplot(2, 1, 2);
plot(time, M5T, ‘b-‘, ‘DisplayName’, ‘M5T [Nm]’);
xlabel(‘Time (s)’);
ylabel(‘M5T [Nm]’);
title(‘M5T vs. Time’);
legend(‘show’);
legend;
hold off;
[~, maxIdx] = max(T5);
maxTime = time(maxIdx);
zeroCrossIdx = find(T5(maxIdx:end) <= 0, 1, ‘first’) + maxIdx – 1;
if isempty(zeroCrossIdx)
timeToZero = NaN;
disp(‘Data does not return to zero after maximum.’);
else
timeToZero = time(zeroCrossIdx) – maxTime;
disp(timeToZero);
end
% Find the index where interpolated T5 matches M5
matchIndex = find(T5 == M5T);
if isempty(matchIndex)
disp(‘T5 does not match M5 ‘);
else
matchTime = commonTime(matchIndex);
fprintf(‘T5 matches M5 at t = %.2f seconds (interpolated).n’, matchTime);
end I am trying to read multiple groups and channels of a TDMS file and doing some graphing and calculations at the end. I need to be able to acceses any channel or group that I want to use in the graphs or calcualtions, I would really apperciate it if someone had any advice on sliming the code down it currently takes 6 mins to run which is a really long time.
defaultFolder = ‘C:UserslillypColostateLute,Chris – EM-TRAS internalMatlab’;
addpath(defaultFolder);
fileFilter = ‘*.tdms’;
[fileName, filepath] = uigetfile(fullfile(defaultFolder, fileFilter), ‘Select a TDMS file’);
if fileName ~= 0
fullFilePath = fullfile(filepath, fileName);
disp([‘Selected file: ‘, fullFilePath]);
else
disp(‘No file selected.’);
end
fileName = fullFilePath;
group_Time = "Torques";
channel_Time = "Timestamp";
tdmsreadprop(fileName, "ChannelGroupName",group_Time, "ChannelName", channel_Time);
data = tdmsread(fileName, "ChannelGroupName",group_Time, "ChannelName", channel_Time);
time = data{1};
if istable(time)
time = table2array(time);
elseif isdatetime(time)
time = seconds(time – time(1));
end
% Speed readings%
group_N1 = "Rotary encoders";
channel_N1 = "N1 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N1, "ChannelName", channel_N1);
data = tdmsread(fileName, "ChannelGroupName",group_N1, "ChannelName", channel_N1);
N1 = data{1};
group_N2 = "Rotary encoders";
channel_N2 = "N2 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N2, "ChannelName", channel_N2);
data = tdmsread(fileName, "ChannelGroupName",group_N2, "ChannelName", channel_N2);
N2 = data{1};
group_N3 = "Rotary encoders";
channel_N3 = "N3 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N3, "ChannelName", channel_N3);
data = tdmsread(fileName, "ChannelGroupName",group_N3, "ChannelName", channel_N3);
N3 = data{1};
group_N4 = "Rotary encoders";
channel_N4 = "N4 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N4, "ChannelName", channel_N4);
data = tdmsread(fileName, "ChannelGroupName",group_N4, "ChannelName", channel_N4);
N4 = data{1};
group_N5 = "Rotary encoders";
channel_N5 = "N5 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N5, "ChannelName", channel_N5);
data = tdmsread(fileName, "ChannelGroupName",group_N5, "ChannelName", channel_N5);
N5 = data{1};
group_N6 = "Rotary encoders";
channel_N6 = "N6 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N6, "ChannelName", channel_N6);
data = tdmsread(fileName, "ChannelGroupName",group_N6, "ChannelName", channel_N6);
N6 = data{1};
group_N7 = "Rotary encoders";
channel_N7 = "N7 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N7, "ChannelName", channel_N7);
data = tdmsread(fileName, "ChannelGroupName",group_N7, "ChannelName", channel_N7);
N7 = data{1};
group_N8 = "Rotary encoders";
channel_N8 = "N8 [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_N8, "ChannelName", channel_N8);
data = tdmsread(fileName, "ChannelGroupName",group_N8, "ChannelName", channel_N8);
N8 = data{1};
% Torque readings%
group_T1 = "Torques";
channel_T1 = "T1 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T1, "ChannelName", channel_T1);
data = tdmsread(fileName, "ChannelGroupName",group_T1, "ChannelName", channel_T1);
T1 = data{1};
group_T2 = "Torques";
channel_T2 = "T2 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T2, "ChannelName", channel_T2);
data = tdmsread(fileName, "ChannelGroupName",group_T2, "ChannelName", channel_T2);
T2 = data{1};
group_T3 = "Torques";
channel_T3 = "T3 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T3, "ChannelName", channel_T3);
data = tdmsread(fileName, "ChannelGroupName",group_T3, "ChannelName", channel_T3);
T3 = data{1};
group_T4 = "Torques";
channel_T4 = "T4 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T4, "ChannelName", channel_T4);
data = tdmsread(fileName, "ChannelGroupName",group_T4, "ChannelName", channel_T4);
T4 = data{1};
group_T5 = "Torques";
channel_T5 = "T5 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T5, "ChannelName", channel_T5);
data = tdmsread(fileName, "ChannelGroupName",group_T5, "ChannelName", channel_T5);
T5 = data{1};
group_T6 = "Torques";
channel_T6 = "T6 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T6, "ChannelName", channel_T6);
data = tdmsread(fileName, "ChannelGroupName",group_T6, "ChannelName", channel_T6);
T6 = data{1};
group_T7 = "Torques";
channel_T7 = "T7 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T7, "ChannelName", channel_T7);
data = tdmsread(fileName, "ChannelGroupName",group_T7, "ChannelName", channel_T7);
T7 = data{1};
group_T8 = "Torques";
channel_T8 = "T8 [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_T8, "ChannelName", channel_T8);
data = tdmsread(fileName, "ChannelGroupName",group_T8, "ChannelName", channel_T8);
T8 = data{1};
%Current readings%
group_I1a = "Motor voltages and currents";
channel_I1a = "I1a [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I1a, "ChannelName", channel_I1a);
data = tdmsread(fileName, "ChannelGroupName",group_I1a, "ChannelName", channel_I1a);
I1a = data{1};
group_I1b = "Motor voltages and currents";
channel_I1b = "I1b [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I1b, "ChannelName", channel_I1b);
data = tdmsread(fileName, "ChannelGroupName",group_I1b, "ChannelName", channel_I1b);
I1b = data{1};
group_I1c = "Motor voltages and currents";
channel_I1c = "I1c [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I1c, "ChannelName", channel_I1c);
data = tdmsread(fileName, "ChannelGroupName",group_I1c, "ChannelName", channel_I1c);
I1c = data{1};
group_I2a = "Motor voltages and currents";
channel_I2a = "I2a [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I2a, "ChannelName", channel_I2a);
data = tdmsread(fileName, "ChannelGroupName",group_I2a, "ChannelName", channel_I2a);
I2a = data{1};
group_I2b = "Motor voltages and currents";
channel_I2b = "I2b [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I2b, "ChannelName", channel_I2b);
data = tdmsread(fileName, "ChannelGroupName",group_I2b, "ChannelName", channel_I2b);
I2b = data{1};
group_I2c = "Motor voltages and currents";
channel_I2c = "I2c [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I2c, "ChannelName", channel_I2c);
data = tdmsread(fileName, "ChannelGroupName",group_I2c, "ChannelName", channel_I2c);
I2c = data{1};
group_I3a = "Motor voltages and currents";
channel_I3a = "I3a [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I3a, "ChannelName", channel_I3a);
data = tdmsread(fileName, "ChannelGroupName",group_I3a, "ChannelName", channel_I3a);
I3a = data{1};
group_I3b = "Motor voltages and currents";
channel_I3b = "I3b [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I3b, "ChannelName", channel_I3b);
data = tdmsread(fileName, "ChannelGroupName",group_I3b, "ChannelName", channel_I3b);
I3b = data{1};
group_I3c = "Motor voltages and currents";
channel_I3c = "I3c [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I3c, "ChannelName", channel_I3c);
data = tdmsread(fileName, "ChannelGroupName",group_I3c, "ChannelName", channel_I3c);
I3c = data{1};
group_I4a = "Motor voltages and currents";
channel_I4a = "I4a [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I4a, "ChannelName", channel_I4a);
data = tdmsread(fileName, "ChannelGroupName",group_I4a, "ChannelName", channel_I4a);
I4a = data{1};
group_I4b = "Motor voltages and currents";
channel_I4b = "I4b [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I4b, "ChannelName", channel_I4b);
data = tdmsread(fileName, "ChannelGroupName",group_I4b, "ChannelName", channel_I4b);
I4b = data{1};
group_I4c = "Motor voltages and currents";
channel_I4c = "I4c [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_I4c, "ChannelName", channel_I4c);
data = tdmsread(fileName, "ChannelGroupName",group_I4c, "ChannelName", channel_I4c);
I4c = data{1};
group_IDC = "Motor voltages and currents";
channel_IDC = "IDC [A]";
tdmsreadprop(fileName, "ChannelGroupName",group_IDC, "ChannelName", channel_IDC);
data = tdmsread(fileName, "ChannelGroupName",group_IDC, "ChannelName", channel_IDC);
IDC = data{1};
%Voltage readings%
group_V1ab = "Motor voltages and currents";
channel_V1ab = "V1ab [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V1ab, "ChannelName", channel_V1ab);
data = tdmsread(fileName, "ChannelGroupName",group_V1ab, "ChannelName", channel_V1ab);
V1ab = data{1};
group_V1bc = "Motor voltages and currents";
channel_V1bc = "V1bc [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V1bc, "ChannelName", channel_V1bc);
data = tdmsread(fileName, "ChannelGroupName",group_V1bc, "ChannelName", channel_V1bc);
V1bc = data{1};
group_V1ca = "Motor voltages and currents";
channel_V1ca = "V1ca [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V1ca, "ChannelName", channel_V1ca);
data = tdmsread(fileName, "ChannelGroupName",group_V1ca, "ChannelName", channel_V1ca);
V1ca = data{1};
group_V2ab = "Motor voltages and currents";
channel_V2ab = "V2ab [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V2ab, "ChannelName", channel_V2ab);
data = tdmsread(fileName, "ChannelGroupName",group_V2ab, "ChannelName", channel_V2ab);
V2ab = data{1};
group_V2bc = "Motor voltages and currents";
channel_V2bc = "V2bc [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V2bc, "ChannelName", channel_V2bc);
data = tdmsread(fileName, "ChannelGroupName",group_V2bc, "ChannelName", channel_V2bc);
V2bc = data{1};
group_V2ca = "Motor voltages and currents";
channel_V2ca = "V2ca [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V2ca, "ChannelName", channel_V2ca);
data = tdmsread(fileName, "ChannelGroupName",group_V2ca, "ChannelName", channel_V2ca);
V2ca = data{1};
group_V3ab = "Motor voltages and currents";
channel_V3ab = "V3ab [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V3ab, "ChannelName", channel_V3ab);
data = tdmsread(fileName, "ChannelGroupName",group_V3ab, "ChannelName", channel_V3ab);
V3ab = data{1};
group_V3bc = "Motor voltages and currents";
channel_V3bc = "V3bc [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V3bc, "ChannelName", channel_V3bc);
data = tdmsread(fileName, "ChannelGroupName",group_V3bc, "ChannelName", channel_V3bc);
V3bc = data{1};
group_V3ca = "Motor voltages and currents";
channel_V3ca = "V3ca [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V3ca, "ChannelName", channel_V3ca);
data = tdmsread(fileName, "ChannelGroupName",group_V3ca, "ChannelName", channel_V3ca);
V3ca = data{1};
group_V4ab = "Motor voltages and currents";
channel_V4ab = "V4ab [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V4ab, "ChannelName", channel_V4ab);
data = tdmsread(fileName, "ChannelGroupName",group_V4ab, "ChannelName", channel_V4ab);
V4ab = data{1};
group_V4bc = "Motor voltages and currents";
channel_V4bc = "V4bc [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V4bc, "ChannelName", channel_V4bc);
data = tdmsread(fileName, "ChannelGroupName",group_V4bc, "ChannelName", channel_V4bc);
V4bc = data{1};
group_V4ca = "Motor voltages and currents";
channel_V4ca = "V4ca [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_V4ca, "ChannelName", channel_V4ca);
data = tdmsread(fileName, "ChannelGroupName",group_V4ca, "ChannelName", channel_V4ca);
V4ca = data{1};
group_VDC = "Motor voltages and currents";
channel_VDC = "VDC [V]";
tdmsreadprop(fileName, "ChannelGroupName",group_VDC, "ChannelName", channel_VDC);
data = tdmsread(fileName, "ChannelGroupName",group_VDC, "ChannelName", channel_VDC);
VDC = data{1};
% Control Commands- Speed
group_M5S = "Control commands";
channel_M5S = "M5 speed cmd [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_M5S, "ChannelName", channel_M5S);
data = tdmsread(fileName, "ChannelGroupName",group_M5S, "ChannelName", channel_M5S);
M5S = data{1};
group_M6S = "Control commands";
channel_M6S = "M6 speed cmd [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_M6S, "ChannelName", channel_M6S);
data = tdmsread(fileName, "ChannelGroupName",group_M6S, "ChannelName", channel_M6S);
M6S = data{1};
group_M7S = "Control commands";
channel_M7S = "M7 speed cmd [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_M7S, "ChannelName", channel_M7S);
data = tdmsread(fileName, "ChannelGroupName",group_M7S, "ChannelName", channel_M7S);
M7S = data{1};
group_M8S = "Control commands";
channel_M8S = "M8 speed cmd [RPM]";
tdmsreadprop(fileName, "ChannelGroupName",group_M8S, "ChannelName", channel_M8S);
data = tdmsread(fileName, "ChannelGroupName",group_M8S, "ChannelName", channel_M8S);
M8S = data{1};
% Control Commands- Torque
group_M5T = "Control commands";
channel_M5T = "M5 torque cmd [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_M5T, "ChannelName", channel_M5T);
data = tdmsread(fileName, "ChannelGroupName",group_M5T, "ChannelName", channel_M5T);
M5T = data{1};
group_M6T = "Control commands";
channel_M6T = "M6 torque cmd [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_M6T, "ChannelName", channel_M6T);
data = tdmsread(fileName, "ChannelGroupName",group_M6T, "ChannelName", channel_M6T);
M6T = data{1};
group_M7T = "Control commands";
channel_M7T = "M7 torque cmd [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_M7T, "ChannelName", channel_M7T);
data = tdmsread(fileName, "ChannelGroupName",group_M7T, "ChannelName", channel_M7T);
M7T = data{1};
group_M8T = "Control commands";
channel_M8T = "M8 torque cmd [Nm]";
tdmsreadprop(fileName, "ChannelGroupName",group_M8T, "ChannelName", channel_M8T);
data = tdmsread(fileName, "ChannelGroupName",group_M8T, "ChannelName", channel_M8T);
M8T = data{1};
%ARRAYS
N1 = table2array(N1);
N2 = table2array(N2);
N3 = table2array(N3);
N4 = table2array(N4);
N5 = table2array(N5);
N6 = table2array(N6);
N7 = table2array(N7);
N8 = table2array(N8);
T1 = table2array(T1);
T2 = table2array(T2);
T3 = table2array(T3);
T4 = table2array(T4);
T5 = table2array(T5);
T6 = table2array(T6);
T7 = table2array(T7);
T8 = table2array(T8);
I1a = table2array(I1a);
I2a = table2array(I2a);
I3a = table2array(I3a);
I4a = table2array(I4a);
I1b = table2array(I1b);
I2b = table2array(I2b);
I3b = table2array(I3b);
I4b = table2array(I4b);
I1c = table2array(I1c);
I2c = table2array(I2c);
I3c = table2array(I3c);
I4c = table2array(I4c);
IDC = table2array(IDC);
V1ab = table2array(V1ab);
V2ab = table2array(V2ab);
V3ab = table2array(V3ab);
V4ab = table2array(V4ab);
V1bc = table2array(V1bc);
V2bc = table2array(V2bc);
V3bc = table2array(V3bc);
V4bc = table2array(V4bc);
V1ca = table2array(V1ca);
V2ca = table2array(V2ca);
V3ca = table2array(V3ca);
V4ca = table2array(V4ca);
VDC= table2array(VDC);
M5S = table2array(M5S);
M6S = table2array(M6S);
M7S = table2array(M7S);
M8S = table2array(M8S);
M5T = table2array(M5T);
M6T = table2array(M6T);
M7T = table2array(M7T);
M8T = table2array(M8T);
% GRAPHS AND TIME STAMPS
minLength_1 = min([length(time), length(T1), length(I1a)]);
minLength_2 = min([length(time), length(T1), length(M5T)]);
time = time(1:minLength_1);
T5 = T5(1:minLength_1);
I1a = I1a(1:minLength_1);
M5T = M5T(1:minLength_2);
figure;
hold on;
subplot(2, 1, 1);
plot(time, T5, ‘r-‘, ‘DisplayName’, ‘T5 [Nm]’);
xlabel(‘Time (s)’);
ylabel(‘T5 [Nm]’);
title(‘T5 vs. Time’);
legend(‘show’);
subplot(2, 1, 2);
plot(time, M5T, ‘b-‘, ‘DisplayName’, ‘M5T [Nm]’);
xlabel(‘Time (s)’);
ylabel(‘M5T [Nm]’);
title(‘M5T vs. Time’);
legend(‘show’);
legend;
hold off;
[~, maxIdx] = max(T5);
maxTime = time(maxIdx);
zeroCrossIdx = find(T5(maxIdx:end) <= 0, 1, ‘first’) + maxIdx – 1;
if isempty(zeroCrossIdx)
timeToZero = NaN;
disp(‘Data does not return to zero after maximum.’);
else
timeToZero = time(zeroCrossIdx) – maxTime;
disp(timeToZero);
end
% Find the index where interpolated T5 matches M5
matchIndex = find(T5 == M5T);
if isempty(matchIndex)
disp(‘T5 does not match M5 ‘);
else
matchTime = commonTime(matchIndex);
fprintf(‘T5 matches M5 at t = %.2f seconds (interpolated).n’, matchTime);
end #tdms, #tdmsread MATLAB Answers — New Questions
How to remove DC component in FFT?
I succesfully plotted my FFT with MATLAB discussion help. Now I could not remove the DC component at 0Hz. Which shows me a very high amplitude. Can any one suggest me an idea?
data1 = xlsread(‘Reading 1.xlsx’) ; %Loading Sensor data from Excel file
t = data1 (1:512,2); %Selecting Time vector
s = data1 (1:512,3); %Selecting Z axis vibrations
L = numel(t); %Signal length
Ts = mean(diff(t)); %Sampling interval
Fs = 1/Ts; %Sampling frequency
Fn = Fs/2; %Nyquist frequency
FTs = fft(s)/L; %Fast fourier transform (s- data)
Fv = linspace(0,1, fix(L/2)+1)*Fn; %Frequency vector
Iv = 1:numel(Fv); %Index vector
subplot(2, 1, 1); %plotting top pane
plot(t,s); %Acceleration vs time
set(gca,’xlim’,[1 50]); %Scale to fit
grid; %Grids on
title (‘Acceleration vs time’);
xlabel(‘time(s)’);
ylabel(‘Acceleration’);
subplot(2, 1, 2); %Plotting bottom pane
plot(Fv, abs(FTs(Iv))*2,’red’); %FFT – Amplitude vs Frequency
grid
title (‘Fast fourier transform’);
xlabel(‘Frequency (Hz)’);
ylabel (‘Amplitude (m)’);I succesfully plotted my FFT with MATLAB discussion help. Now I could not remove the DC component at 0Hz. Which shows me a very high amplitude. Can any one suggest me an idea?
data1 = xlsread(‘Reading 1.xlsx’) ; %Loading Sensor data from Excel file
t = data1 (1:512,2); %Selecting Time vector
s = data1 (1:512,3); %Selecting Z axis vibrations
L = numel(t); %Signal length
Ts = mean(diff(t)); %Sampling interval
Fs = 1/Ts; %Sampling frequency
Fn = Fs/2; %Nyquist frequency
FTs = fft(s)/L; %Fast fourier transform (s- data)
Fv = linspace(0,1, fix(L/2)+1)*Fn; %Frequency vector
Iv = 1:numel(Fv); %Index vector
subplot(2, 1, 1); %plotting top pane
plot(t,s); %Acceleration vs time
set(gca,’xlim’,[1 50]); %Scale to fit
grid; %Grids on
title (‘Acceleration vs time’);
xlabel(‘time(s)’);
ylabel(‘Acceleration’);
subplot(2, 1, 2); %Plotting bottom pane
plot(Fv, abs(FTs(Iv))*2,’red’); %FFT – Amplitude vs Frequency
grid
title (‘Fast fourier transform’);
xlabel(‘Frequency (Hz)’);
ylabel (‘Amplitude (m)’); I succesfully plotted my FFT with MATLAB discussion help. Now I could not remove the DC component at 0Hz. Which shows me a very high amplitude. Can any one suggest me an idea?
data1 = xlsread(‘Reading 1.xlsx’) ; %Loading Sensor data from Excel file
t = data1 (1:512,2); %Selecting Time vector
s = data1 (1:512,3); %Selecting Z axis vibrations
L = numel(t); %Signal length
Ts = mean(diff(t)); %Sampling interval
Fs = 1/Ts; %Sampling frequency
Fn = Fs/2; %Nyquist frequency
FTs = fft(s)/L; %Fast fourier transform (s- data)
Fv = linspace(0,1, fix(L/2)+1)*Fn; %Frequency vector
Iv = 1:numel(Fv); %Index vector
subplot(2, 1, 1); %plotting top pane
plot(t,s); %Acceleration vs time
set(gca,’xlim’,[1 50]); %Scale to fit
grid; %Grids on
title (‘Acceleration vs time’);
xlabel(‘time(s)’);
ylabel(‘Acceleration’);
subplot(2, 1, 2); %Plotting bottom pane
plot(Fv, abs(FTs(Iv))*2,’red’); %FFT – Amplitude vs Frequency
grid
title (‘Fast fourier transform’);
xlabel(‘Frequency (Hz)’);
ylabel (‘Amplitude (m)’); dc, fft, amplitude MATLAB Answers — New Questions
How do I import my MATLAB path preferences when I install MATLAB on new computers?
I have a new computer with Matlab 2024b newly installed on it and am looking to import preference settings (mainly desktop layouts, font settings, and keyboard shortcuts) that I use in my Matlab installations on other computers. I am aware of this previous thread, but it is not applicable here, because it assumes that a previous release of Matlab resides on the computer. That is not the case for me, as the intended computer is brand new.
I have been able to import my desktop layouts manually by copying over the ___Layout.xml files that reside in the prefdir. However, I am not sure which prefdir file holds the fonts and keyboard shortcuts, so I have not been able to import those. Does anyone know which prefdir files are the applicable ones? I have tried copying over matlab.prf, but it doesn’t seem to have any effect.I have a new computer with Matlab 2024b newly installed on it and am looking to import preference settings (mainly desktop layouts, font settings, and keyboard shortcuts) that I use in my Matlab installations on other computers. I am aware of this previous thread, but it is not applicable here, because it assumes that a previous release of Matlab resides on the computer. That is not the case for me, as the intended computer is brand new.
I have been able to import my desktop layouts manually by copying over the ___Layout.xml files that reside in the prefdir. However, I am not sure which prefdir file holds the fonts and keyboard shortcuts, so I have not been able to import those. Does anyone know which prefdir files are the applicable ones? I have tried copying over matlab.prf, but it doesn’t seem to have any effect. I have a new computer with Matlab 2024b newly installed on it and am looking to import preference settings (mainly desktop layouts, font settings, and keyboard shortcuts) that I use in my Matlab installations on other computers. I am aware of this previous thread, but it is not applicable here, because it assumes that a previous release of Matlab resides on the computer. That is not the case for me, as the intended computer is brand new.
I have been able to import my desktop layouts manually by copying over the ___Layout.xml files that reside in the prefdir. However, I am not sure which prefdir file holds the fonts and keyboard shortcuts, so I have not been able to import those. Does anyone know which prefdir files are the applicable ones? I have tried copying over matlab.prf, but it doesn’t seem to have any effect. preferences, desktop, prefdir, keyboard shortcuts, fonts MATLAB Answers — New Questions
Command Window prompt stays in view during Run Section
I find, in R2024b (I haven’t checked other versions), then when running sub-sections of code, for example with , the command line prompt stays visible while the computation is in progress. This is not the case when running normally, and I am wondering if it is a deliberate design choice. If so, I wonder if there is some preference setting that will deactivate this, as I find it makes it a bit more difficult to see when Matlab is busy (in spite of the ‘Busy’ notification in the lower left of the Matlab desktop).I find, in R2024b (I haven’t checked other versions), then when running sub-sections of code, for example with , the command line prompt stays visible while the computation is in progress. This is not the case when running normally, and I am wondering if it is a deliberate design choice. If so, I wonder if there is some preference setting that will deactivate this, as I find it makes it a bit more difficult to see when Matlab is busy (in spite of the ‘Busy’ notification in the lower left of the Matlab desktop). I find, in R2024b (I haven’t checked other versions), then when running sub-sections of code, for example with , the command line prompt stays visible while the computation is in progress. This is not the case when running normally, and I am wondering if it is a deliberate design choice. If so, I wonder if there is some preference setting that will deactivate this, as I find it makes it a bit more difficult to see when Matlab is busy (in spite of the ‘Busy’ notification in the lower left of the Matlab desktop). run section, prompt MATLAB Answers — New Questions
Is MATLAB supported on iPad, iPhone, iPod Touch?
Is it possible to download and install MATLAB to an iPad, iPhone, or iPod Touch?Is it possible to download and install MATLAB to an iPad, iPhone, or iPod Touch? Is it possible to download and install MATLAB to an iPad, iPhone, or iPod Touch? MATLAB Answers — New Questions
Plot large files with timestamp
I have a large file and try to load it into MATLAB and plot it with timestamp.I have a large file and try to load it into MATLAB and plot it with timestamp. I have a large file and try to load it into MATLAB and plot it with timestamp. timestamp, plot MATLAB Answers — New Questions