Category: Matlab
Category Archives: Matlab
Jacobian calculation of symbolic variables which are function of other variables.
Hi everyone,
I am trying to find the jacobian for a transformation matrix. I am using symbolic variables (T, l, m, n). Each of these variables are function of 4 others variables (delta1 delta2 delta3 and delta4), as:
syms u v w p q r phi theta psi x y z;
syms delta1 delta2 delta3 delta4;
% Aerodynamics
V = sqrt(u^2 + v^2 + w^2);
q_bar = (1/2) * rho * V^2;
m = (-1.35* Kf * delta1^2) + (1.35* Kf * delta2^2) + (1.35*K * Kf * delta3^2) + (-1.35* Kf * delta4^2);
l = (0.904* Kf *delta1^2) + (-0.904* Kf *delta2^2) + (0.904* Kf *delta3^2) + (-0.904* Kf *delta4^2);
n = (Km * delta1^2) + (Km * delta2^2) – (Km * delta3^2) – (Km * delta4^2);
T1= (Kf * delta1^2);
T2= (Kf * delta2^2);
T3= (Kf * delta3^2);
T4= (Kf * delta4^2);
T= T1 + T2 + T3 + T4;
phi_dot = p + tan(theta) * (q * sin(phi) + r * cos(phi));
theta_dot = q * cos(phi) – r * sin(phi);
psi_dot = (q * sin(phi) + r * cos(phi)) / cos(theta);
x_dot = cos(psi)*cos(theta)*u + (cos(psi)*sin(theta)*sin(phi) – sin(psi)*cos(phi))*v + (cos(psi)*sin(theta)*cos(phi) + sin(psi)*sin(phi))*w;
y_dot = (sin(psi)*cos(theta))*u + (sin(psi)*sin(theta)*sin(phi) + cos(psi)*cos(phi))*v + (sin(psi)*sin(theta)*cos(phi) – cos(psi)*sin(phi))*w;
z_dot = -sin(theta)*u + cos(theta)*sin(phi)*v + cos(theta)*cos(phi)*w;
f_x = – mass*g * sin(theta);
f_y = mass*g * sin(phi) * cos(theta);
f_z = mass*g * cos(phi) * cos(theta) – T ;
u_dot = r*v – q*w + (1/mass) * (f_x);
v_dot = p*w – r*u + (1/mass) * (f_y);
w_dot = q*u – p*v + (1/mass) * (f_z);
p_dot = gam(1)*p*q – gam(2)*q*r + gam(3)*l + gam(4)*n;
q_dot = gam(5)*p*r – gam(6)*(p^2 – r^2) + (1/J_yy) * m;
r_dot = gam(7)*p*q – gam(1)*q*r + gam(4)*l + gam(8)*n;
% Collect dynamics
f = [ x_dot;
y_dot;
z_dot;
phi_dot;
theta_dot;
psi_dot;
u_dot;
v_dot;
w_dot;
p_dot;
q_dot;
r_dot];
jacobian(f,[T l m n]);
So when calculating jacobian(f,[T l m n]) , i have the error:
"Invalid argument at position 2. Argument must be a variable, a symfun without a formula, or a symfun whose formula is a variable."
Can someone please give me a solution to the problem ?Hi everyone,
I am trying to find the jacobian for a transformation matrix. I am using symbolic variables (T, l, m, n). Each of these variables are function of 4 others variables (delta1 delta2 delta3 and delta4), as:
syms u v w p q r phi theta psi x y z;
syms delta1 delta2 delta3 delta4;
% Aerodynamics
V = sqrt(u^2 + v^2 + w^2);
q_bar = (1/2) * rho * V^2;
m = (-1.35* Kf * delta1^2) + (1.35* Kf * delta2^2) + (1.35*K * Kf * delta3^2) + (-1.35* Kf * delta4^2);
l = (0.904* Kf *delta1^2) + (-0.904* Kf *delta2^2) + (0.904* Kf *delta3^2) + (-0.904* Kf *delta4^2);
n = (Km * delta1^2) + (Km * delta2^2) – (Km * delta3^2) – (Km * delta4^2);
T1= (Kf * delta1^2);
T2= (Kf * delta2^2);
T3= (Kf * delta3^2);
T4= (Kf * delta4^2);
T= T1 + T2 + T3 + T4;
phi_dot = p + tan(theta) * (q * sin(phi) + r * cos(phi));
theta_dot = q * cos(phi) – r * sin(phi);
psi_dot = (q * sin(phi) + r * cos(phi)) / cos(theta);
x_dot = cos(psi)*cos(theta)*u + (cos(psi)*sin(theta)*sin(phi) – sin(psi)*cos(phi))*v + (cos(psi)*sin(theta)*cos(phi) + sin(psi)*sin(phi))*w;
y_dot = (sin(psi)*cos(theta))*u + (sin(psi)*sin(theta)*sin(phi) + cos(psi)*cos(phi))*v + (sin(psi)*sin(theta)*cos(phi) – cos(psi)*sin(phi))*w;
z_dot = -sin(theta)*u + cos(theta)*sin(phi)*v + cos(theta)*cos(phi)*w;
f_x = – mass*g * sin(theta);
f_y = mass*g * sin(phi) * cos(theta);
f_z = mass*g * cos(phi) * cos(theta) – T ;
u_dot = r*v – q*w + (1/mass) * (f_x);
v_dot = p*w – r*u + (1/mass) * (f_y);
w_dot = q*u – p*v + (1/mass) * (f_z);
p_dot = gam(1)*p*q – gam(2)*q*r + gam(3)*l + gam(4)*n;
q_dot = gam(5)*p*r – gam(6)*(p^2 – r^2) + (1/J_yy) * m;
r_dot = gam(7)*p*q – gam(1)*q*r + gam(4)*l + gam(8)*n;
% Collect dynamics
f = [ x_dot;
y_dot;
z_dot;
phi_dot;
theta_dot;
psi_dot;
u_dot;
v_dot;
w_dot;
p_dot;
q_dot;
r_dot];
jacobian(f,[T l m n]);
So when calculating jacobian(f,[T l m n]) , i have the error:
"Invalid argument at position 2. Argument must be a variable, a symfun without a formula, or a symfun whose formula is a variable."
Can someone please give me a solution to the problem ? Hi everyone,
I am trying to find the jacobian for a transformation matrix. I am using symbolic variables (T, l, m, n). Each of these variables are function of 4 others variables (delta1 delta2 delta3 and delta4), as:
syms u v w p q r phi theta psi x y z;
syms delta1 delta2 delta3 delta4;
% Aerodynamics
V = sqrt(u^2 + v^2 + w^2);
q_bar = (1/2) * rho * V^2;
m = (-1.35* Kf * delta1^2) + (1.35* Kf * delta2^2) + (1.35*K * Kf * delta3^2) + (-1.35* Kf * delta4^2);
l = (0.904* Kf *delta1^2) + (-0.904* Kf *delta2^2) + (0.904* Kf *delta3^2) + (-0.904* Kf *delta4^2);
n = (Km * delta1^2) + (Km * delta2^2) – (Km * delta3^2) – (Km * delta4^2);
T1= (Kf * delta1^2);
T2= (Kf * delta2^2);
T3= (Kf * delta3^2);
T4= (Kf * delta4^2);
T= T1 + T2 + T3 + T4;
phi_dot = p + tan(theta) * (q * sin(phi) + r * cos(phi));
theta_dot = q * cos(phi) – r * sin(phi);
psi_dot = (q * sin(phi) + r * cos(phi)) / cos(theta);
x_dot = cos(psi)*cos(theta)*u + (cos(psi)*sin(theta)*sin(phi) – sin(psi)*cos(phi))*v + (cos(psi)*sin(theta)*cos(phi) + sin(psi)*sin(phi))*w;
y_dot = (sin(psi)*cos(theta))*u + (sin(psi)*sin(theta)*sin(phi) + cos(psi)*cos(phi))*v + (sin(psi)*sin(theta)*cos(phi) – cos(psi)*sin(phi))*w;
z_dot = -sin(theta)*u + cos(theta)*sin(phi)*v + cos(theta)*cos(phi)*w;
f_x = – mass*g * sin(theta);
f_y = mass*g * sin(phi) * cos(theta);
f_z = mass*g * cos(phi) * cos(theta) – T ;
u_dot = r*v – q*w + (1/mass) * (f_x);
v_dot = p*w – r*u + (1/mass) * (f_y);
w_dot = q*u – p*v + (1/mass) * (f_z);
p_dot = gam(1)*p*q – gam(2)*q*r + gam(3)*l + gam(4)*n;
q_dot = gam(5)*p*r – gam(6)*(p^2 – r^2) + (1/J_yy) * m;
r_dot = gam(7)*p*q – gam(1)*q*r + gam(4)*l + gam(8)*n;
% Collect dynamics
f = [ x_dot;
y_dot;
z_dot;
phi_dot;
theta_dot;
psi_dot;
u_dot;
v_dot;
w_dot;
p_dot;
q_dot;
r_dot];
jacobian(f,[T l m n]);
So when calculating jacobian(f,[T l m n]) , i have the error:
"Invalid argument at position 2. Argument must be a variable, a symfun without a formula, or a symfun whose formula is a variable."
Can someone please give me a solution to the problem ? jacobian MATLAB Answers — New Questions
multiplying a function handle by a constant
For the code below I am trying to find the polynomial equation that represents the system. There are 4-2nd ODE equations I have made them into 4-1st ODE the first order differentials become "y1,y2,y3and y4" and the 2nd order differentials become a first order. I then put all 4 into a matlabFunction, how do I multiple the function handle by the constant"h" with out getting the error "Operator ‘*’ is not supported for operands of type ‘function_handle’."?
The rest of the code works if working with a single differential equation fx(x,y,t) with only "x,y,t" but in my equations I have "Xf,Xr,Xb,theta" and "Vf,Vr,Vb,omega" that I have chosen to represent as "x1,x2,x3,x4" and "y1,y2,y3,y4" respectively. The next question is will I run into problems here as well?
I am not that expirenced working with matlabFunction command to know how to get this to work. The project requires me to use 2 different numerical methods to find the polynomial equation that best fits so I cannot use "Polyfit" to get the polynomial that best fits. Any suggestions that can help me to get this to work would be appreciated.
clear,close,clc
%______________________________________________________________SOLUITION_2_Heun’s_Method_(for second order differential equations)_&__Least-Square_Nethod____________________________________________________________%
%4 Equations representing the system working with
% MfXf"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)-Xf’)-(Kf*Xf);
% MrXr"=Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)-(Kr*Xr) ;
% MbXb"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)]-Xf’)+Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t);
% Ic*theta"={-[Ksf(Xf-(L1*theta))*L1]-[Bsf(Xf’-(L1*theta’))*L1]+[Ksr(Xr+(L2*theta))*L2]+[Bsr(Xr’+(L2*theta’))*L2]+[fa(t)*L3]};
clc
clear
%————————————————-SYSTEM_PARAMETERS———————————————————————————————————————————————————-
Ic=1356; %kg-m^2
Mb=730; %kg
Mf=59; %kg
Mr=45; %kg
Kf=23000; %N/m
Ksf=18750; %N/m
Kr=16182; %N/m
Ksr=12574; %N/m
Bsf=100; %N*s/m
Bsr=100; %N*s/m
L1=1.45; %m
L2=1.39; %m
L3=0.67; %m
t=[0:20]; % time from 0 to 20 seconds
n=4; %order of the polynomial
%Initial Conditions-system at rest therefore x(0)=0 dXf/dt(0)=0 dXr/dt(0)=0 dXb/dt(0)=0 dtheta/dt(0)=0 ;
%time from 0 to 20 h=dx=5;
x0=0; %x at initial condition
y0=0; %y at initial condition
t0=0; %t at the start
dx=5; %delta(x) or h
h=dx;
tm=20; %what value of (x) you are ending at
Xf = sym(‘x1’); %x1=Xf
Xr = sym(‘x2’); %x2=Xr
Xb = sym(‘x3’); %x3=Xb
theta = sym(‘x4’); %x4=theta
Vf = sym(‘y1′); %y1=Xf’ = Vf = dXf/dt = Xf_1
Vr = sym(‘y2′); %y2=Xr’ = Vr = dXr/dt = Xr_1
Vb = sym(‘y3′); %y3=Xb’ = Vb = dXb/dt = Xb_1
omega = sym(‘y4’); %y4=theta’= omega = dtheta/dt = theta_1
t = sym(‘t’);
% MfXf"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)-Xf’)-(Kf*Xf);
% Vf’=(1/Mf)(Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)-Xf’)-(Kf*Xf));
% MrXr"=Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)-(Kr*Xr) ;
% Vr’=(1/Mr)(Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)-(Kr*Xr)) ;
% MbXb"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)]-Xf’)+Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t);
% Vb’=(1/Mb)(-Ksf([Xb-(L1*theta)]-Xf)-Bsf([Xb’-(L1*theta’)]-Xf’)-Ksr([Xb+(L2*theta)]-Xr)-Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t));
% Ic*theta"={-[Ksf(Xf-(L1*theta))*L1]-[Bsf(Xf’-(L1*theta’))*L1]+[Ksr(Xr+(L2*theta))*L2]+[Bsr(Xr’+(L2*theta’))*L2]+[fa(t)*L3]};
% omega’=(1/Ic){[-Ksf*Xf + Ksf((L1)^2)*theta)] + [-Bsf*Vf*L1 + Bsf*Vf*L1 + Bsf((L1)^2)*omega)] + [Ksr*Xr*L2 + Ksr((L2)^2)*theta)] + [Bsr*Vr*L2 + Bsr((L2)^2)*omega)*L2] + [fa(t)*L3]};
Xf_2=(Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Vb-(L1*omega)-Vf)-(Kf*Xf)))/Mf;
Xr_2=(Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Vb+(L2*omega))-Vr)-(Kr*Xr))/Mr;
Xb_2=(Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Vb-(L1*theta’))-Vf)+Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Vb+(L2*omega))-Vr)+(10*exp(-(5*t))))/Mb;
theta_2=((-(Ksf*(Xf-(L1^2*theta))*L1)-(Bsf*(Vf-(L1*omega))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*(Vr+(L2*omega))*L2)+((10*exp(-(5*t)))*L3)))/Ic;
Eqns=[Xf_2; Xr_2; Xb_2; theta_2];
F1=matlabFunction(Eqns,’Vars’,{‘x1′,’x2′,’x3′,’x4′,’y1′,’y2′,’y3′,’y4′,’t’})
%==INPUT SECTION for Euler’s and Heun’s==%
fx=@(x,y,t)y;
fy=@(x,y,t)F1;
%==CALCULATIONS SECTION==%
tn=t0:h:tm;
xn(1) = x0;
yn(1) = y0;
for i=1:length(tn)
%==EULER’S METHOD
xn(i+1)=xn(i)+fx(xn(i),yn(i),tn(i))*h;
yn(i+1)=yn(i)+fy(xn(i),yn(i),tn(i))*h;
%==NEXT 3 LINES ARE FOR HEUN’S METHOD
tn(i+1)=tn(i)+h;
xn(i+1)=xn(i)+0.5*(fx(xn(i),yn(i),tn(i))+fx(xn(i+1),yn(i+1),tn(i+1)))*h;
yn(i+1)=yn(i)+0.5*(fy(xn(i),yn(i),tn(i))+fy(xn(i+1),yn(i+1),tn(i+1)))*h;
fprintf(‘t=%0.2ft x=%0.3ft y=%0.3fn’,tn(i),xn(i),yn(i))
end
%%%LEAST SQUARE METHOD-FINDS POLYNOMIAL FOR GIVEN DATA SET%%%%%
%INPUT SECTION for Least-Square
X=xn;
Y=yn;
%%__CALCULATIONS SECTION__%%
k=length(X); %NUMBER OF AVAILABLE DATA POINTS
m=n+1; %SIZE OF THE COEFFICENT MATRIX
A=zeros(m,m); %COEFFICENT MATRIX
for j=1:m
for i=1:m
A(j,i)=sum(X.^(i+j-2));
end
end
B=zeros(m,1); %FORCING FUNCTION VECTOR
for i=1:m;
B(i)=sum(Y.*X.^(i-1));
end
a1=AB %COEFFICIENTS FOR THE POLYNOMINAL–> y=a0+a1*x+a2*x^2….an*x^n CAN BE REPLACED BY GAUSSIAN ELIMINATION
%%%%%=========GAUSSIAN ELIMINATION TO FIND "a"========%%%%%%
%%%INPUT SECTION
%CALCULATION SECTION
AB=[A B]; %Augumentent matrix
R=size(AB,1); %# OF ROWS IN AB
C=size(AB,2); %# OF COLUMNS IN AB
%%%%FOWARD ELIMINATION SECTION
for J=1:R-1
[M,I]=max(abs(AB(J:R,J))); %M=MAXIMUM VALUE, I=LOCATION OF THE MAXIMUM VALUE IN THE 1ST ROW
temp=AB(J,:);
AB(J,:)=AB(I+(J-1),:);
AB(I+(J-1),:)=temp;
for i=(J+1):R;
if AB(i,J)~=0;
AB(i,:)=AB(i,:)-(AB(i,J)/AB(J,J))*AB(J,:);
end
end
end
%%%%BACKWARDS SUBSTITUTION
a(R)=AB(R,C)/AB(R,R);
for i=R-1:-1:1
a(i)=(AB(i,C)-AB(i,i+1:R)*a(i+1:R)’)/AB(i,i);
end
disp(a)
syms X
P=0;
for i=1:m;
TT=a(i)*X^(i-1); %T=INDIVIDUAL POLYNOMIAL TERMS
P=P+TT;
end
display(P)
%========END OF GAUSSIAN ELIMINATION=======%%%%%%%%For the code below I am trying to find the polynomial equation that represents the system. There are 4-2nd ODE equations I have made them into 4-1st ODE the first order differentials become "y1,y2,y3and y4" and the 2nd order differentials become a first order. I then put all 4 into a matlabFunction, how do I multiple the function handle by the constant"h" with out getting the error "Operator ‘*’ is not supported for operands of type ‘function_handle’."?
The rest of the code works if working with a single differential equation fx(x,y,t) with only "x,y,t" but in my equations I have "Xf,Xr,Xb,theta" and "Vf,Vr,Vb,omega" that I have chosen to represent as "x1,x2,x3,x4" and "y1,y2,y3,y4" respectively. The next question is will I run into problems here as well?
I am not that expirenced working with matlabFunction command to know how to get this to work. The project requires me to use 2 different numerical methods to find the polynomial equation that best fits so I cannot use "Polyfit" to get the polynomial that best fits. Any suggestions that can help me to get this to work would be appreciated.
clear,close,clc
%______________________________________________________________SOLUITION_2_Heun’s_Method_(for second order differential equations)_&__Least-Square_Nethod____________________________________________________________%
%4 Equations representing the system working with
% MfXf"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)-Xf’)-(Kf*Xf);
% MrXr"=Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)-(Kr*Xr) ;
% MbXb"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)]-Xf’)+Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t);
% Ic*theta"={-[Ksf(Xf-(L1*theta))*L1]-[Bsf(Xf’-(L1*theta’))*L1]+[Ksr(Xr+(L2*theta))*L2]+[Bsr(Xr’+(L2*theta’))*L2]+[fa(t)*L3]};
clc
clear
%————————————————-SYSTEM_PARAMETERS———————————————————————————————————————————————————-
Ic=1356; %kg-m^2
Mb=730; %kg
Mf=59; %kg
Mr=45; %kg
Kf=23000; %N/m
Ksf=18750; %N/m
Kr=16182; %N/m
Ksr=12574; %N/m
Bsf=100; %N*s/m
Bsr=100; %N*s/m
L1=1.45; %m
L2=1.39; %m
L3=0.67; %m
t=[0:20]; % time from 0 to 20 seconds
n=4; %order of the polynomial
%Initial Conditions-system at rest therefore x(0)=0 dXf/dt(0)=0 dXr/dt(0)=0 dXb/dt(0)=0 dtheta/dt(0)=0 ;
%time from 0 to 20 h=dx=5;
x0=0; %x at initial condition
y0=0; %y at initial condition
t0=0; %t at the start
dx=5; %delta(x) or h
h=dx;
tm=20; %what value of (x) you are ending at
Xf = sym(‘x1’); %x1=Xf
Xr = sym(‘x2’); %x2=Xr
Xb = sym(‘x3’); %x3=Xb
theta = sym(‘x4’); %x4=theta
Vf = sym(‘y1′); %y1=Xf’ = Vf = dXf/dt = Xf_1
Vr = sym(‘y2′); %y2=Xr’ = Vr = dXr/dt = Xr_1
Vb = sym(‘y3′); %y3=Xb’ = Vb = dXb/dt = Xb_1
omega = sym(‘y4’); %y4=theta’= omega = dtheta/dt = theta_1
t = sym(‘t’);
% MfXf"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)-Xf’)-(Kf*Xf);
% Vf’=(1/Mf)(Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)-Xf’)-(Kf*Xf));
% MrXr"=Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)-(Kr*Xr) ;
% Vr’=(1/Mr)(Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)-(Kr*Xr)) ;
% MbXb"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)]-Xf’)+Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t);
% Vb’=(1/Mb)(-Ksf([Xb-(L1*theta)]-Xf)-Bsf([Xb’-(L1*theta’)]-Xf’)-Ksr([Xb+(L2*theta)]-Xr)-Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t));
% Ic*theta"={-[Ksf(Xf-(L1*theta))*L1]-[Bsf(Xf’-(L1*theta’))*L1]+[Ksr(Xr+(L2*theta))*L2]+[Bsr(Xr’+(L2*theta’))*L2]+[fa(t)*L3]};
% omega’=(1/Ic){[-Ksf*Xf + Ksf((L1)^2)*theta)] + [-Bsf*Vf*L1 + Bsf*Vf*L1 + Bsf((L1)^2)*omega)] + [Ksr*Xr*L2 + Ksr((L2)^2)*theta)] + [Bsr*Vr*L2 + Bsr((L2)^2)*omega)*L2] + [fa(t)*L3]};
Xf_2=(Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Vb-(L1*omega)-Vf)-(Kf*Xf)))/Mf;
Xr_2=(Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Vb+(L2*omega))-Vr)-(Kr*Xr))/Mr;
Xb_2=(Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Vb-(L1*theta’))-Vf)+Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Vb+(L2*omega))-Vr)+(10*exp(-(5*t))))/Mb;
theta_2=((-(Ksf*(Xf-(L1^2*theta))*L1)-(Bsf*(Vf-(L1*omega))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*(Vr+(L2*omega))*L2)+((10*exp(-(5*t)))*L3)))/Ic;
Eqns=[Xf_2; Xr_2; Xb_2; theta_2];
F1=matlabFunction(Eqns,’Vars’,{‘x1′,’x2′,’x3′,’x4′,’y1′,’y2′,’y3′,’y4′,’t’})
%==INPUT SECTION for Euler’s and Heun’s==%
fx=@(x,y,t)y;
fy=@(x,y,t)F1;
%==CALCULATIONS SECTION==%
tn=t0:h:tm;
xn(1) = x0;
yn(1) = y0;
for i=1:length(tn)
%==EULER’S METHOD
xn(i+1)=xn(i)+fx(xn(i),yn(i),tn(i))*h;
yn(i+1)=yn(i)+fy(xn(i),yn(i),tn(i))*h;
%==NEXT 3 LINES ARE FOR HEUN’S METHOD
tn(i+1)=tn(i)+h;
xn(i+1)=xn(i)+0.5*(fx(xn(i),yn(i),tn(i))+fx(xn(i+1),yn(i+1),tn(i+1)))*h;
yn(i+1)=yn(i)+0.5*(fy(xn(i),yn(i),tn(i))+fy(xn(i+1),yn(i+1),tn(i+1)))*h;
fprintf(‘t=%0.2ft x=%0.3ft y=%0.3fn’,tn(i),xn(i),yn(i))
end
%%%LEAST SQUARE METHOD-FINDS POLYNOMIAL FOR GIVEN DATA SET%%%%%
%INPUT SECTION for Least-Square
X=xn;
Y=yn;
%%__CALCULATIONS SECTION__%%
k=length(X); %NUMBER OF AVAILABLE DATA POINTS
m=n+1; %SIZE OF THE COEFFICENT MATRIX
A=zeros(m,m); %COEFFICENT MATRIX
for j=1:m
for i=1:m
A(j,i)=sum(X.^(i+j-2));
end
end
B=zeros(m,1); %FORCING FUNCTION VECTOR
for i=1:m;
B(i)=sum(Y.*X.^(i-1));
end
a1=AB %COEFFICIENTS FOR THE POLYNOMINAL–> y=a0+a1*x+a2*x^2….an*x^n CAN BE REPLACED BY GAUSSIAN ELIMINATION
%%%%%=========GAUSSIAN ELIMINATION TO FIND "a"========%%%%%%
%%%INPUT SECTION
%CALCULATION SECTION
AB=[A B]; %Augumentent matrix
R=size(AB,1); %# OF ROWS IN AB
C=size(AB,2); %# OF COLUMNS IN AB
%%%%FOWARD ELIMINATION SECTION
for J=1:R-1
[M,I]=max(abs(AB(J:R,J))); %M=MAXIMUM VALUE, I=LOCATION OF THE MAXIMUM VALUE IN THE 1ST ROW
temp=AB(J,:);
AB(J,:)=AB(I+(J-1),:);
AB(I+(J-1),:)=temp;
for i=(J+1):R;
if AB(i,J)~=0;
AB(i,:)=AB(i,:)-(AB(i,J)/AB(J,J))*AB(J,:);
end
end
end
%%%%BACKWARDS SUBSTITUTION
a(R)=AB(R,C)/AB(R,R);
for i=R-1:-1:1
a(i)=(AB(i,C)-AB(i,i+1:R)*a(i+1:R)’)/AB(i,i);
end
disp(a)
syms X
P=0;
for i=1:m;
TT=a(i)*X^(i-1); %T=INDIVIDUAL POLYNOMIAL TERMS
P=P+TT;
end
display(P)
%========END OF GAUSSIAN ELIMINATION=======%%%%%%%% For the code below I am trying to find the polynomial equation that represents the system. There are 4-2nd ODE equations I have made them into 4-1st ODE the first order differentials become "y1,y2,y3and y4" and the 2nd order differentials become a first order. I then put all 4 into a matlabFunction, how do I multiple the function handle by the constant"h" with out getting the error "Operator ‘*’ is not supported for operands of type ‘function_handle’."?
The rest of the code works if working with a single differential equation fx(x,y,t) with only "x,y,t" but in my equations I have "Xf,Xr,Xb,theta" and "Vf,Vr,Vb,omega" that I have chosen to represent as "x1,x2,x3,x4" and "y1,y2,y3,y4" respectively. The next question is will I run into problems here as well?
I am not that expirenced working with matlabFunction command to know how to get this to work. The project requires me to use 2 different numerical methods to find the polynomial equation that best fits so I cannot use "Polyfit" to get the polynomial that best fits. Any suggestions that can help me to get this to work would be appreciated.
clear,close,clc
%______________________________________________________________SOLUITION_2_Heun’s_Method_(for second order differential equations)_&__Least-Square_Nethod____________________________________________________________%
%4 Equations representing the system working with
% MfXf"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)-Xf’)-(Kf*Xf);
% MrXr"=Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)-(Kr*Xr) ;
% MbXb"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)]-Xf’)+Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t);
% Ic*theta"={-[Ksf(Xf-(L1*theta))*L1]-[Bsf(Xf’-(L1*theta’))*L1]+[Ksr(Xr+(L2*theta))*L2]+[Bsr(Xr’+(L2*theta’))*L2]+[fa(t)*L3]};
clc
clear
%————————————————-SYSTEM_PARAMETERS———————————————————————————————————————————————————-
Ic=1356; %kg-m^2
Mb=730; %kg
Mf=59; %kg
Mr=45; %kg
Kf=23000; %N/m
Ksf=18750; %N/m
Kr=16182; %N/m
Ksr=12574; %N/m
Bsf=100; %N*s/m
Bsr=100; %N*s/m
L1=1.45; %m
L2=1.39; %m
L3=0.67; %m
t=[0:20]; % time from 0 to 20 seconds
n=4; %order of the polynomial
%Initial Conditions-system at rest therefore x(0)=0 dXf/dt(0)=0 dXr/dt(0)=0 dXb/dt(0)=0 dtheta/dt(0)=0 ;
%time from 0 to 20 h=dx=5;
x0=0; %x at initial condition
y0=0; %y at initial condition
t0=0; %t at the start
dx=5; %delta(x) or h
h=dx;
tm=20; %what value of (x) you are ending at
Xf = sym(‘x1’); %x1=Xf
Xr = sym(‘x2’); %x2=Xr
Xb = sym(‘x3’); %x3=Xb
theta = sym(‘x4’); %x4=theta
Vf = sym(‘y1′); %y1=Xf’ = Vf = dXf/dt = Xf_1
Vr = sym(‘y2′); %y2=Xr’ = Vr = dXr/dt = Xr_1
Vb = sym(‘y3′); %y3=Xb’ = Vb = dXb/dt = Xb_1
omega = sym(‘y4’); %y4=theta’= omega = dtheta/dt = theta_1
t = sym(‘t’);
% MfXf"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)-Xf’)-(Kf*Xf);
% Vf’=(1/Mf)(Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)-Xf’)-(Kf*Xf));
% MrXr"=Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)-(Kr*Xr) ;
% Vr’=(1/Mr)(Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)-(Kr*Xr)) ;
% MbXb"=Ksf([Xb-(L1*theta)]-Xf)+Bsf([Xb’-(L1*theta’)]-Xf’)+Ksr([Xb+(L2*theta)]-Xr)+Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t);
% Vb’=(1/Mb)(-Ksf([Xb-(L1*theta)]-Xf)-Bsf([Xb’-(L1*theta’)]-Xf’)-Ksr([Xb+(L2*theta)]-Xr)-Bsr([Xb’+(L2*theta’)]-Xr’)+fa(t));
% Ic*theta"={-[Ksf(Xf-(L1*theta))*L1]-[Bsf(Xf’-(L1*theta’))*L1]+[Ksr(Xr+(L2*theta))*L2]+[Bsr(Xr’+(L2*theta’))*L2]+[fa(t)*L3]};
% omega’=(1/Ic){[-Ksf*Xf + Ksf((L1)^2)*theta)] + [-Bsf*Vf*L1 + Bsf*Vf*L1 + Bsf((L1)^2)*omega)] + [Ksr*Xr*L2 + Ksr((L2)^2)*theta)] + [Bsr*Vr*L2 + Bsr((L2)^2)*omega)*L2] + [fa(t)*L3]};
Xf_2=(Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Vb-(L1*omega)-Vf)-(Kf*Xf)))/Mf;
Xr_2=(Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Vb+(L2*omega))-Vr)-(Kr*Xr))/Mr;
Xb_2=(Ksf*((Xb-(L1*theta))-Xf)+Bsf*((Vb-(L1*theta’))-Vf)+Ksr*((Xb+(L2*theta))-Xr)+Bsr*((Vb+(L2*omega))-Vr)+(10*exp(-(5*t))))/Mb;
theta_2=((-(Ksf*(Xf-(L1^2*theta))*L1)-(Bsf*(Vf-(L1*omega))*L1)+(Ksr*(Xr+(L2*theta))*L2)+(Bsr*(Vr+(L2*omega))*L2)+((10*exp(-(5*t)))*L3)))/Ic;
Eqns=[Xf_2; Xr_2; Xb_2; theta_2];
F1=matlabFunction(Eqns,’Vars’,{‘x1′,’x2′,’x3′,’x4′,’y1′,’y2′,’y3′,’y4′,’t’})
%==INPUT SECTION for Euler’s and Heun’s==%
fx=@(x,y,t)y;
fy=@(x,y,t)F1;
%==CALCULATIONS SECTION==%
tn=t0:h:tm;
xn(1) = x0;
yn(1) = y0;
for i=1:length(tn)
%==EULER’S METHOD
xn(i+1)=xn(i)+fx(xn(i),yn(i),tn(i))*h;
yn(i+1)=yn(i)+fy(xn(i),yn(i),tn(i))*h;
%==NEXT 3 LINES ARE FOR HEUN’S METHOD
tn(i+1)=tn(i)+h;
xn(i+1)=xn(i)+0.5*(fx(xn(i),yn(i),tn(i))+fx(xn(i+1),yn(i+1),tn(i+1)))*h;
yn(i+1)=yn(i)+0.5*(fy(xn(i),yn(i),tn(i))+fy(xn(i+1),yn(i+1),tn(i+1)))*h;
fprintf(‘t=%0.2ft x=%0.3ft y=%0.3fn’,tn(i),xn(i),yn(i))
end
%%%LEAST SQUARE METHOD-FINDS POLYNOMIAL FOR GIVEN DATA SET%%%%%
%INPUT SECTION for Least-Square
X=xn;
Y=yn;
%%__CALCULATIONS SECTION__%%
k=length(X); %NUMBER OF AVAILABLE DATA POINTS
m=n+1; %SIZE OF THE COEFFICENT MATRIX
A=zeros(m,m); %COEFFICENT MATRIX
for j=1:m
for i=1:m
A(j,i)=sum(X.^(i+j-2));
end
end
B=zeros(m,1); %FORCING FUNCTION VECTOR
for i=1:m;
B(i)=sum(Y.*X.^(i-1));
end
a1=AB %COEFFICIENTS FOR THE POLYNOMINAL–> y=a0+a1*x+a2*x^2….an*x^n CAN BE REPLACED BY GAUSSIAN ELIMINATION
%%%%%=========GAUSSIAN ELIMINATION TO FIND "a"========%%%%%%
%%%INPUT SECTION
%CALCULATION SECTION
AB=[A B]; %Augumentent matrix
R=size(AB,1); %# OF ROWS IN AB
C=size(AB,2); %# OF COLUMNS IN AB
%%%%FOWARD ELIMINATION SECTION
for J=1:R-1
[M,I]=max(abs(AB(J:R,J))); %M=MAXIMUM VALUE, I=LOCATION OF THE MAXIMUM VALUE IN THE 1ST ROW
temp=AB(J,:);
AB(J,:)=AB(I+(J-1),:);
AB(I+(J-1),:)=temp;
for i=(J+1):R;
if AB(i,J)~=0;
AB(i,:)=AB(i,:)-(AB(i,J)/AB(J,J))*AB(J,:);
end
end
end
%%%%BACKWARDS SUBSTITUTION
a(R)=AB(R,C)/AB(R,R);
for i=R-1:-1:1
a(i)=(AB(i,C)-AB(i,i+1:R)*a(i+1:R)’)/AB(i,i);
end
disp(a)
syms X
P=0;
for i=1:m;
TT=a(i)*X^(i-1); %T=INDIVIDUAL POLYNOMIAL TERMS
P=P+TT;
end
display(P)
%========END OF GAUSSIAN ELIMINATION=======%%%%%%%% multiplying function handle, polynomial that best fits, heun’s method MATLAB Answers — New Questions
Solving a system of ODE over different intervals (with different conditions on parameters)
Good Evening dear Matlab Community,
Now that my first part of code works, I have the ambition to make it a little complicated but I can’t figure out how to implement my plan in matlab:
in the code below you can see that I’m solving a system of two differential equations. Now my challenge is that I would like to solve it with different conditions on certain parameters over the full interval l. I would like to divide the full interval l into sections i each itself divided into two zones, j.
Each section i starts with a conductive zone (j=1) of say l=3 meter for which:
Aap=lcont
Acp=Aap
hap=17
kap=0.018
And ends with a convection zone (j=2) of l=2 meter for which following is true:
Aap=2*lcont
Acp=0
hap=20
kap=0.02
After this, comes the conductive zone of the next section…
I am confused about how to define indices for the sections and zones and whether I need to include loops within the functions corresponding to my ODE in order to solve my system. I have tried (and failed) by introducing following lines within the script of my ODE functions:
for j=1
Aap=lcont
Acp=Aap
hap=17
kap=0.018
end
for j=2
Aap=2*lcont
Acp=0
hap=20
kap=0.02
end
If I define the array J=[1 2], how can I make sure that the same indice is used to solve both ODE for each section?
Ideally I would even like to be able to build-in variation for the parameters of the conductive zone between two different sections (like for section 1 and j=1, hap=17 and for section 2 and j=1, hap=5) but I guess once I understand how to implement it for one case, I’ll be able to extend it to further! 🙂
[l,y]=ode45(@myODE,[0 45],[0.48,30]);
plot(l,y(:,:))
function dy = myODE(l,y)
global u
u=y(1);
global Tp
Tp=y(2);
dTpdl = myODE1(l,u,Tp);
dudl = myODE2(l,u,Tp);
dy = [dudl;dTpdl];
end
function dudl = myODE2(l,u,Tp)
lcont=2.855;
Psatp = 0.13*exp(18-3800/(Tp+227.03));
Phi= 1-exp(-(47*u^2+0.1*Tp*u^1.06));
Ppw= Psatp*Phi;
dudl=-(kap*Aap)*(Ppw/(Tp+273.15)-0.19);
end
function dTpdl=myODE1(l,u,Tp)
lcont=2.855;
hcp0=0.65;
Psatp = 0.13*exp(18-3800/(Tp+227.03));
Phi= 1-exp(-(47*u^2+0.1*Tp*u^1.06));
Ppw= Psatp*Phi;
DHs = 0.1*(u^1.1)*((Tp+275.15)^2)*(1-Phi)/Phi;
DHvap = 1000*(2501-2.3*Tp);
DHevap = DHs+DHvap;
dTpdl=((hcp0+0.955*u)*(140-Tp)*Acp+hap*(100-Tp)*Aap+DHevap*(-kap*Aap)*(Ppw/(Tp+273)-0.19))/(1.4+4.18*u);
endGood Evening dear Matlab Community,
Now that my first part of code works, I have the ambition to make it a little complicated but I can’t figure out how to implement my plan in matlab:
in the code below you can see that I’m solving a system of two differential equations. Now my challenge is that I would like to solve it with different conditions on certain parameters over the full interval l. I would like to divide the full interval l into sections i each itself divided into two zones, j.
Each section i starts with a conductive zone (j=1) of say l=3 meter for which:
Aap=lcont
Acp=Aap
hap=17
kap=0.018
And ends with a convection zone (j=2) of l=2 meter for which following is true:
Aap=2*lcont
Acp=0
hap=20
kap=0.02
After this, comes the conductive zone of the next section…
I am confused about how to define indices for the sections and zones and whether I need to include loops within the functions corresponding to my ODE in order to solve my system. I have tried (and failed) by introducing following lines within the script of my ODE functions:
for j=1
Aap=lcont
Acp=Aap
hap=17
kap=0.018
end
for j=2
Aap=2*lcont
Acp=0
hap=20
kap=0.02
end
If I define the array J=[1 2], how can I make sure that the same indice is used to solve both ODE for each section?
Ideally I would even like to be able to build-in variation for the parameters of the conductive zone between two different sections (like for section 1 and j=1, hap=17 and for section 2 and j=1, hap=5) but I guess once I understand how to implement it for one case, I’ll be able to extend it to further! 🙂
[l,y]=ode45(@myODE,[0 45],[0.48,30]);
plot(l,y(:,:))
function dy = myODE(l,y)
global u
u=y(1);
global Tp
Tp=y(2);
dTpdl = myODE1(l,u,Tp);
dudl = myODE2(l,u,Tp);
dy = [dudl;dTpdl];
end
function dudl = myODE2(l,u,Tp)
lcont=2.855;
Psatp = 0.13*exp(18-3800/(Tp+227.03));
Phi= 1-exp(-(47*u^2+0.1*Tp*u^1.06));
Ppw= Psatp*Phi;
dudl=-(kap*Aap)*(Ppw/(Tp+273.15)-0.19);
end
function dTpdl=myODE1(l,u,Tp)
lcont=2.855;
hcp0=0.65;
Psatp = 0.13*exp(18-3800/(Tp+227.03));
Phi= 1-exp(-(47*u^2+0.1*Tp*u^1.06));
Ppw= Psatp*Phi;
DHs = 0.1*(u^1.1)*((Tp+275.15)^2)*(1-Phi)/Phi;
DHvap = 1000*(2501-2.3*Tp);
DHevap = DHs+DHvap;
dTpdl=((hcp0+0.955*u)*(140-Tp)*Acp+hap*(100-Tp)*Aap+DHevap*(-kap*Aap)*(Ppw/(Tp+273)-0.19))/(1.4+4.18*u);
end Good Evening dear Matlab Community,
Now that my first part of code works, I have the ambition to make it a little complicated but I can’t figure out how to implement my plan in matlab:
in the code below you can see that I’m solving a system of two differential equations. Now my challenge is that I would like to solve it with different conditions on certain parameters over the full interval l. I would like to divide the full interval l into sections i each itself divided into two zones, j.
Each section i starts with a conductive zone (j=1) of say l=3 meter for which:
Aap=lcont
Acp=Aap
hap=17
kap=0.018
And ends with a convection zone (j=2) of l=2 meter for which following is true:
Aap=2*lcont
Acp=0
hap=20
kap=0.02
After this, comes the conductive zone of the next section…
I am confused about how to define indices for the sections and zones and whether I need to include loops within the functions corresponding to my ODE in order to solve my system. I have tried (and failed) by introducing following lines within the script of my ODE functions:
for j=1
Aap=lcont
Acp=Aap
hap=17
kap=0.018
end
for j=2
Aap=2*lcont
Acp=0
hap=20
kap=0.02
end
If I define the array J=[1 2], how can I make sure that the same indice is used to solve both ODE for each section?
Ideally I would even like to be able to build-in variation for the parameters of the conductive zone between two different sections (like for section 1 and j=1, hap=17 and for section 2 and j=1, hap=5) but I guess once I understand how to implement it for one case, I’ll be able to extend it to further! 🙂
[l,y]=ode45(@myODE,[0 45],[0.48,30]);
plot(l,y(:,:))
function dy = myODE(l,y)
global u
u=y(1);
global Tp
Tp=y(2);
dTpdl = myODE1(l,u,Tp);
dudl = myODE2(l,u,Tp);
dy = [dudl;dTpdl];
end
function dudl = myODE2(l,u,Tp)
lcont=2.855;
Psatp = 0.13*exp(18-3800/(Tp+227.03));
Phi= 1-exp(-(47*u^2+0.1*Tp*u^1.06));
Ppw= Psatp*Phi;
dudl=-(kap*Aap)*(Ppw/(Tp+273.15)-0.19);
end
function dTpdl=myODE1(l,u,Tp)
lcont=2.855;
hcp0=0.65;
Psatp = 0.13*exp(18-3800/(Tp+227.03));
Phi= 1-exp(-(47*u^2+0.1*Tp*u^1.06));
Ppw= Psatp*Phi;
DHs = 0.1*(u^1.1)*((Tp+275.15)^2)*(1-Phi)/Phi;
DHvap = 1000*(2501-2.3*Tp);
DHevap = DHs+DHvap;
dTpdl=((hcp0+0.955*u)*(140-Tp)*Acp+hap*(100-Tp)*Aap+DHevap*(-kap*Aap)*(Ppw/(Tp+273)-0.19))/(1.4+4.18*u);
end indice, ode, code, functions, loops MATLAB Answers — New Questions
Cannot open file anymore when converting Nifti to DICOM
I have a script where I convert MRI nifti files to DICOM. This used to work but now I get an error when trying to create a new folder and saving the converted files into that folder:
First steps work (Part I):
%% load data
% REVISIT – adapt all text between ‘apostrophes’
patientID = ‘patient180’; % this is the folder with the specific patient data
patientIn = fullfile(‘7Tseg_Brainlab’, patientID); % this is the folder where the patient folders are in
patientFolder = fullfile… % this is the whole path to the patientIn folder
(‘here is whole path’,patientIn);
addpath(genpath(patientIn));
dicom_template = ‘00501_3D_TSE_0.7mm’; % this is the original dicom that is used for the new dicom header
Then with this part I get an error (Part II):
% note: the [space] before the second ‘ after the names is necessary,
% otherwise you will get an error
cmdNiftiToDicom = [‘niftitodicom.exe -o’ patientFolder ‘LmSTN ‘ patientFolder ‘7T2LRmSTN.nii.gz ‘ patientFolder ‘0501_3D_TSE_0.7mm0001.dcm –sagittal ‘ ‘–series-description LmSTN ‘];
statusNiftiToDicom = system( cmdNiftiToDicom );
cmdNiftiToDicom = [‘niftitodicom.exe -o’ patientFolder ‘RmSTN ‘ patientFolder ‘7T2LRmSTN.nii.gz ‘ patientFolder ‘0501_3D_TSE_0.7mm0001.dcm –sagittal ‘ ‘–series-description RmSTN ‘];
statusNiftiToDicom = system( cmdNiftiToDicom);
So what I want is 2 folders, named ‘LmSTN’ and ‘RmSTN’. This used to work and now I get the error saying ‘Cannot open file’, but I do use the correct path.I have a script where I convert MRI nifti files to DICOM. This used to work but now I get an error when trying to create a new folder and saving the converted files into that folder:
First steps work (Part I):
%% load data
% REVISIT – adapt all text between ‘apostrophes’
patientID = ‘patient180’; % this is the folder with the specific patient data
patientIn = fullfile(‘7Tseg_Brainlab’, patientID); % this is the folder where the patient folders are in
patientFolder = fullfile… % this is the whole path to the patientIn folder
(‘here is whole path’,patientIn);
addpath(genpath(patientIn));
dicom_template = ‘00501_3D_TSE_0.7mm’; % this is the original dicom that is used for the new dicom header
Then with this part I get an error (Part II):
% note: the [space] before the second ‘ after the names is necessary,
% otherwise you will get an error
cmdNiftiToDicom = [‘niftitodicom.exe -o’ patientFolder ‘LmSTN ‘ patientFolder ‘7T2LRmSTN.nii.gz ‘ patientFolder ‘0501_3D_TSE_0.7mm0001.dcm –sagittal ‘ ‘–series-description LmSTN ‘];
statusNiftiToDicom = system( cmdNiftiToDicom );
cmdNiftiToDicom = [‘niftitodicom.exe -o’ patientFolder ‘RmSTN ‘ patientFolder ‘7T2LRmSTN.nii.gz ‘ patientFolder ‘0501_3D_TSE_0.7mm0001.dcm –sagittal ‘ ‘–series-description RmSTN ‘];
statusNiftiToDicom = system( cmdNiftiToDicom);
So what I want is 2 folders, named ‘LmSTN’ and ‘RmSTN’. This used to work and now I get the error saying ‘Cannot open file’, but I do use the correct path. I have a script where I convert MRI nifti files to DICOM. This used to work but now I get an error when trying to create a new folder and saving the converted files into that folder:
First steps work (Part I):
%% load data
% REVISIT – adapt all text between ‘apostrophes’
patientID = ‘patient180’; % this is the folder with the specific patient data
patientIn = fullfile(‘7Tseg_Brainlab’, patientID); % this is the folder where the patient folders are in
patientFolder = fullfile… % this is the whole path to the patientIn folder
(‘here is whole path’,patientIn);
addpath(genpath(patientIn));
dicom_template = ‘00501_3D_TSE_0.7mm’; % this is the original dicom that is used for the new dicom header
Then with this part I get an error (Part II):
% note: the [space] before the second ‘ after the names is necessary,
% otherwise you will get an error
cmdNiftiToDicom = [‘niftitodicom.exe -o’ patientFolder ‘LmSTN ‘ patientFolder ‘7T2LRmSTN.nii.gz ‘ patientFolder ‘0501_3D_TSE_0.7mm0001.dcm –sagittal ‘ ‘–series-description LmSTN ‘];
statusNiftiToDicom = system( cmdNiftiToDicom );
cmdNiftiToDicom = [‘niftitodicom.exe -o’ patientFolder ‘RmSTN ‘ patientFolder ‘7T2LRmSTN.nii.gz ‘ patientFolder ‘0501_3D_TSE_0.7mm0001.dcm –sagittal ‘ ‘–series-description RmSTN ‘];
statusNiftiToDicom = system( cmdNiftiToDicom);
So what I want is 2 folders, named ‘LmSTN’ and ‘RmSTN’. This used to work and now I get the error saying ‘Cannot open file’, but I do use the correct path. nifti, dicom MATLAB Answers — New Questions
Mouse often freezes for several seconds when MATLAB is open, even when not running
When MATLAB is open, my laptop often freezes for several seconds. This happens frequently, about every half a minute or more often. It happens more often when I am actively using MATLAB but it also happens often when I have MATLAB open but not running or typing anything. I tried different releases (2021b and 2024a) and reset my preferences but that didn’t work. Anyone knows how to solve this?When MATLAB is open, my laptop often freezes for several seconds. This happens frequently, about every half a minute or more often. It happens more often when I am actively using MATLAB but it also happens often when I have MATLAB open but not running or typing anything. I tried different releases (2021b and 2024a) and reset my preferences but that didn’t work. Anyone knows how to solve this? When MATLAB is open, my laptop often freezes for several seconds. This happens frequently, about every half a minute or more often. It happens more often when I am actively using MATLAB but it also happens often when I have MATLAB open but not running or typing anything. I tried different releases (2021b and 2024a) and reset my preferences but that didn’t work. Anyone knows how to solve this? freeze MATLAB Answers — New Questions
How can I programmatically link a requirement to a step in test assessment
I want to link my requirements from requirements editor to specific steps in my test assessment block (I also use test scenarios). I was able to create the link between both via mouse-clicks, but I want to link it via a script.
I suppose it is done by the command
slreq.createLink(src,dest)
but I was not able to get the handle / id / url of the step in my test scenario to use as a source (or destination).
If I examine a manually created link it uses the following "adress" to the step in the assessment:
domain: ‘linktype_rmi_simulink’
artifact: ‘C:pathtomodelAutomationExampleUnit.slx’
id: ‘:urn:uuid:4c7edae6-0d2c-4603-96ec-d8f11e1c3afb:52:84’
but where can I find this id ?
thanks in advance !!I want to link my requirements from requirements editor to specific steps in my test assessment block (I also use test scenarios). I was able to create the link between both via mouse-clicks, but I want to link it via a script.
I suppose it is done by the command
slreq.createLink(src,dest)
but I was not able to get the handle / id / url of the step in my test scenario to use as a source (or destination).
If I examine a manually created link it uses the following "adress" to the step in the assessment:
domain: ‘linktype_rmi_simulink’
artifact: ‘C:pathtomodelAutomationExampleUnit.slx’
id: ‘:urn:uuid:4c7edae6-0d2c-4603-96ec-d8f11e1c3afb:52:84’
but where can I find this id ?
thanks in advance !! I want to link my requirements from requirements editor to specific steps in my test assessment block (I also use test scenarios). I was able to create the link between both via mouse-clicks, but I want to link it via a script.
I suppose it is done by the command
slreq.createLink(src,dest)
but I was not able to get the handle / id / url of the step in my test scenario to use as a source (or destination).
If I examine a manually created link it uses the following "adress" to the step in the assessment:
domain: ‘linktype_rmi_simulink’
artifact: ‘C:pathtomodelAutomationExampleUnit.slx’
id: ‘:urn:uuid:4c7edae6-0d2c-4603-96ec-d8f11e1c3afb:52:84’
but where can I find this id ?
thanks in advance !! assessment, step, scenario, requirement, link, programming MATLAB Answers — New Questions
Problems by calculating zero points of a cubic function
Hey there,
I have the following problem: let´s say I want to calculate the zero points of the cubic function:
f(x) = -2 x^3 + x^2 + 0.5 x – 8
I already know the respective solution:
p = roots([-2 1 0.5 -8])
The answer p is a vector with all three possible solutions.
Now my problem:
I would like to vary the third coefficient – that is 0.5 – by several values 0.1, 0.2, … , 0.5
That would be like
x=0.1:0.1:0.5;
p = roots([-2 1 x -8])
The problem is that the respective solutions are wrong.
What is my mistake?
How should I do it instead?
Thx a lot in advance!
Best regards,
TimHey there,
I have the following problem: let´s say I want to calculate the zero points of the cubic function:
f(x) = -2 x^3 + x^2 + 0.5 x – 8
I already know the respective solution:
p = roots([-2 1 0.5 -8])
The answer p is a vector with all three possible solutions.
Now my problem:
I would like to vary the third coefficient – that is 0.5 – by several values 0.1, 0.2, … , 0.5
That would be like
x=0.1:0.1:0.5;
p = roots([-2 1 x -8])
The problem is that the respective solutions are wrong.
What is my mistake?
How should I do it instead?
Thx a lot in advance!
Best regards,
Tim Hey there,
I have the following problem: let´s say I want to calculate the zero points of the cubic function:
f(x) = -2 x^3 + x^2 + 0.5 x – 8
I already know the respective solution:
p = roots([-2 1 0.5 -8])
The answer p is a vector with all three possible solutions.
Now my problem:
I would like to vary the third coefficient – that is 0.5 – by several values 0.1, 0.2, … , 0.5
That would be like
x=0.1:0.1:0.5;
p = roots([-2 1 x -8])
The problem is that the respective solutions are wrong.
What is my mistake?
How should I do it instead?
Thx a lot in advance!
Best regards,
Tim roots polynom or cubic funtion MATLAB Answers — New Questions
Problem using diary with standalone application
I am developing a MATLAB app using the appdesigner (MATLAB version R2019b), which is intented to be used as standalone ‘.exe’ on Windows. For traceablity I wanted to include a log-file of all outputs. The ‘diary()’ function seemed to be a good function for this. In my code I have a lot of ‘disp(…)’ commands (also in code parts that I cannot or do not want to change). The output for these disp-commands works perfectly in the MATLAB command window when I run the application within the MATLAB environment. However, when run it as Windows standalone the behavior is not logical to me: In the WIndows cmd window the output is the same as in the MATLAB command window, but the diary file only logs the output for the ‘startupFcn()’ and the ‘UIFigureCloseRequest()’ functions and not for any callback, e.g. here from a button ‘DispHelloWorldButtonPushed()’.
Does anybody know how to solve this issue and where it comes from? Btw, also the build-in ‘Create log file’ option during compilation shows the same behavior as the ‘diary’ function.
Here is a minimal working example of an app with this behavior:
classdef Test < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
DispHelloWorldButton matlab.ui.control.Button
end
% Callbacks that handle component events
methods (Access = private)
% Code that executes after component creation
function startupFcn(app)
diary(fullfile(pwd,’log.txt’))
diary on
disp(‘Hello World!’)
end
% Button pushed function: DispHelloWorldButton
function DispHelloWorldButtonPushed(app, event)
diary on
disp(‘Button: Hello World!’)
end
% Close request function: UIFigure
function UIFigureCloseRequest(app, event)
disp(‘Bye bye World!’)
diary off
delete(app)
end
end
% Component initialization
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Create UIFigure and hide until all components are created
app.UIFigure = uifigure(‘Visible’, ‘off’);
app.UIFigure.Position = [100 100 640 480];
app.UIFigure.Name = ‘UI Figure’;
app.UIFigure.CloseRequestFcn = createCallbackFcn(app, @UIFigureCloseRequest, true);
% Create DispHelloWorldButton
app.DispHelloWorldButton = uibutton(app.UIFigure, ‘push’);
app.DispHelloWorldButton.ButtonPushedFcn = createCallbackFcn(app, @DispHelloWorldButtonPushed, true);
app.DispHelloWorldButton.Position = [159 161 311 175];
app.DispHelloWorldButton.Text = ‘Disp(”Hello World!”)’;
% Show the figure after all components are created
app.UIFigure.Visible = ‘on’;
end
end
% App creation and deletion
methods (Access = public)
% Construct app
function app = Test
% Create UIFigure and components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.UIFigure)
% Execute the startup function
runStartupFcn(app, @startupFcn)
if nargout == 0
clear app
end
end
% Code that executes before app deletion
function delete(app)
% Delete UIFigure when app is deleted
delete(app.UIFigure)
end
end
endI am developing a MATLAB app using the appdesigner (MATLAB version R2019b), which is intented to be used as standalone ‘.exe’ on Windows. For traceablity I wanted to include a log-file of all outputs. The ‘diary()’ function seemed to be a good function for this. In my code I have a lot of ‘disp(…)’ commands (also in code parts that I cannot or do not want to change). The output for these disp-commands works perfectly in the MATLAB command window when I run the application within the MATLAB environment. However, when run it as Windows standalone the behavior is not logical to me: In the WIndows cmd window the output is the same as in the MATLAB command window, but the diary file only logs the output for the ‘startupFcn()’ and the ‘UIFigureCloseRequest()’ functions and not for any callback, e.g. here from a button ‘DispHelloWorldButtonPushed()’.
Does anybody know how to solve this issue and where it comes from? Btw, also the build-in ‘Create log file’ option during compilation shows the same behavior as the ‘diary’ function.
Here is a minimal working example of an app with this behavior:
classdef Test < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
DispHelloWorldButton matlab.ui.control.Button
end
% Callbacks that handle component events
methods (Access = private)
% Code that executes after component creation
function startupFcn(app)
diary(fullfile(pwd,’log.txt’))
diary on
disp(‘Hello World!’)
end
% Button pushed function: DispHelloWorldButton
function DispHelloWorldButtonPushed(app, event)
diary on
disp(‘Button: Hello World!’)
end
% Close request function: UIFigure
function UIFigureCloseRequest(app, event)
disp(‘Bye bye World!’)
diary off
delete(app)
end
end
% Component initialization
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Create UIFigure and hide until all components are created
app.UIFigure = uifigure(‘Visible’, ‘off’);
app.UIFigure.Position = [100 100 640 480];
app.UIFigure.Name = ‘UI Figure’;
app.UIFigure.CloseRequestFcn = createCallbackFcn(app, @UIFigureCloseRequest, true);
% Create DispHelloWorldButton
app.DispHelloWorldButton = uibutton(app.UIFigure, ‘push’);
app.DispHelloWorldButton.ButtonPushedFcn = createCallbackFcn(app, @DispHelloWorldButtonPushed, true);
app.DispHelloWorldButton.Position = [159 161 311 175];
app.DispHelloWorldButton.Text = ‘Disp(”Hello World!”)’;
% Show the figure after all components are created
app.UIFigure.Visible = ‘on’;
end
end
% App creation and deletion
methods (Access = public)
% Construct app
function app = Test
% Create UIFigure and components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.UIFigure)
% Execute the startup function
runStartupFcn(app, @startupFcn)
if nargout == 0
clear app
end
end
% Code that executes before app deletion
function delete(app)
% Delete UIFigure when app is deleted
delete(app.UIFigure)
end
end
end I am developing a MATLAB app using the appdesigner (MATLAB version R2019b), which is intented to be used as standalone ‘.exe’ on Windows. For traceablity I wanted to include a log-file of all outputs. The ‘diary()’ function seemed to be a good function for this. In my code I have a lot of ‘disp(…)’ commands (also in code parts that I cannot or do not want to change). The output for these disp-commands works perfectly in the MATLAB command window when I run the application within the MATLAB environment. However, when run it as Windows standalone the behavior is not logical to me: In the WIndows cmd window the output is the same as in the MATLAB command window, but the diary file only logs the output for the ‘startupFcn()’ and the ‘UIFigureCloseRequest()’ functions and not for any callback, e.g. here from a button ‘DispHelloWorldButtonPushed()’.
Does anybody know how to solve this issue and where it comes from? Btw, also the build-in ‘Create log file’ option during compilation shows the same behavior as the ‘diary’ function.
Here is a minimal working example of an app with this behavior:
classdef Test < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
DispHelloWorldButton matlab.ui.control.Button
end
% Callbacks that handle component events
methods (Access = private)
% Code that executes after component creation
function startupFcn(app)
diary(fullfile(pwd,’log.txt’))
diary on
disp(‘Hello World!’)
end
% Button pushed function: DispHelloWorldButton
function DispHelloWorldButtonPushed(app, event)
diary on
disp(‘Button: Hello World!’)
end
% Close request function: UIFigure
function UIFigureCloseRequest(app, event)
disp(‘Bye bye World!’)
diary off
delete(app)
end
end
% Component initialization
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Create UIFigure and hide until all components are created
app.UIFigure = uifigure(‘Visible’, ‘off’);
app.UIFigure.Position = [100 100 640 480];
app.UIFigure.Name = ‘UI Figure’;
app.UIFigure.CloseRequestFcn = createCallbackFcn(app, @UIFigureCloseRequest, true);
% Create DispHelloWorldButton
app.DispHelloWorldButton = uibutton(app.UIFigure, ‘push’);
app.DispHelloWorldButton.ButtonPushedFcn = createCallbackFcn(app, @DispHelloWorldButtonPushed, true);
app.DispHelloWorldButton.Position = [159 161 311 175];
app.DispHelloWorldButton.Text = ‘Disp(”Hello World!”)’;
% Show the figure after all components are created
app.UIFigure.Visible = ‘on’;
end
end
% App creation and deletion
methods (Access = public)
% Construct app
function app = Test
% Create UIFigure and components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.UIFigure)
% Execute the startup function
runStartupFcn(app, @startupFcn)
if nargout == 0
clear app
end
end
% Code that executes before app deletion
function delete(app)
% Delete UIFigure when app is deleted
delete(app.UIFigure)
end
end
end standalone, disp, diary, callback, appdesigner MATLAB Answers — New Questions
How can I export .mat file to .xls file?
How can I export .mat file to .xls file? I am using xlswrite(‘filename.xls’) but not working. I have 50×50 deta. Kindly help me.How can I export .mat file to .xls file? I am using xlswrite(‘filename.xls’) but not working. I have 50×50 deta. Kindly help me. How can I export .mat file to .xls file? I am using xlswrite(‘filename.xls’) but not working. I have 50×50 deta. Kindly help me. how can i export .mat file to .xls file? MATLAB Answers — New Questions
Errors in feedback control after setting the input of a prismatic joint to motion/provided by input
Hello, I am currently controlling the prismatic joint actuators of a Stewart platform using Simulink. I have set the input to motion/provided by input in order to change the position of the eight actuators over time. However, when I try to perform feedback control in the simulation, I encounter errors as shown in the image below. Feedback control works when the input is set to force, but why do these errors occur when the input is set to motion? If anyone knows the answer, I would be very grateful for your help.Hello, I am currently controlling the prismatic joint actuators of a Stewart platform using Simulink. I have set the input to motion/provided by input in order to change the position of the eight actuators over time. However, when I try to perform feedback control in the simulation, I encounter errors as shown in the image below. Feedback control works when the input is set to force, but why do these errors occur when the input is set to motion? If anyone knows the answer, I would be very grateful for your help. Hello, I am currently controlling the prismatic joint actuators of a Stewart platform using Simulink. I have set the input to motion/provided by input in order to change the position of the eight actuators over time. However, when I try to perform feedback control in the simulation, I encounter errors as shown in the image below. Feedback control works when the input is set to force, but why do these errors occur when the input is set to motion? If anyone knows the answer, I would be very grateful for your help. simulink, simscape MATLAB Answers — New Questions
Colorbar with a range taken from a variable
Hello,
I have a matrix organized in this way:
M= col1, col2…. col10
col1 and col2 are the x and y position of the data, col10 is a property of this data and it is a number.
I would like to use the numbers in col10 to make a colormap and assign ot every point a specific color that depends on the value in col10.
I did this long time ago, but I don’t remember how, can somebody help me, please?
Thanks
F.Hello,
I have a matrix organized in this way:
M= col1, col2…. col10
col1 and col2 are the x and y position of the data, col10 is a property of this data and it is a number.
I would like to use the numbers in col10 to make a colormap and assign ot every point a specific color that depends on the value in col10.
I did this long time ago, but I don’t remember how, can somebody help me, please?
Thanks
F. Hello,
I have a matrix organized in this way:
M= col1, col2…. col10
col1 and col2 are the x and y position of the data, col10 is a property of this data and it is a number.
I would like to use the numbers in col10 to make a colormap and assign ot every point a specific color that depends on the value in col10.
I did this long time ago, but I don’t remember how, can somebody help me, please?
Thanks
F. plot MATLAB Answers — New Questions
Can the data type of a Simulink PS converter be boolean instead of double/single?
I have a signal. A data type conversion block is being used to convert the data type of the signal to boolean. The signal then goes to Simulink PS converter. Upon doing so the follwoing error pops up.
Request for help to use boolean data type signals with Simulink PS converters.I have a signal. A data type conversion block is being used to convert the data type of the signal to boolean. The signal then goes to Simulink PS converter. Upon doing so the follwoing error pops up.
Request for help to use boolean data type signals with Simulink PS converters. I have a signal. A data type conversion block is being used to convert the data type of the signal to boolean. The signal then goes to Simulink PS converter. Upon doing so the follwoing error pops up.
Request for help to use boolean data type signals with Simulink PS converters. matlab, simscape, ps converters, data type MATLAB Answers — New Questions
MinidroneCompetition track evaluation, how can I build our own tracks?
As the rules introduced, our minidrone will be tested on multiple tracks. Does anyone know who we can build our own tracks for evaluation in the simulink?As the rules introduced, our minidrone will be tested on multiple tracks. Does anyone know who we can build our own tracks for evaluation in the simulink? As the rules introduced, our minidrone will be tested on multiple tracks. Does anyone know who we can build our own tracks for evaluation in the simulink? minidronecompetition MATLAB Answers — New Questions
possible solution to speed up with power function?
Is there any solution to speed up this code? The power function is too expensive. Any help is much appreciated.
tic
N = 1000000;
Linput = 500;
t = 1:Linput;
mTT = rand(N,1);
alf = rand(N,1);
beta = mTT./alf;
faktor = 1./(beta.^alf.*gamma(alf));
A = t.^(alf-1);
B = -t./beta ;
C = faktor.*A.*exp(B);
toc
Elapsed time is 104.574729 seconds.Is there any solution to speed up this code? The power function is too expensive. Any help is much appreciated.
tic
N = 1000000;
Linput = 500;
t = 1:Linput;
mTT = rand(N,1);
alf = rand(N,1);
beta = mTT./alf;
faktor = 1./(beta.^alf.*gamma(alf));
A = t.^(alf-1);
B = -t./beta ;
C = faktor.*A.*exp(B);
toc
Elapsed time is 104.574729 seconds. Is there any solution to speed up this code? The power function is too expensive. Any help is much appreciated.
tic
N = 1000000;
Linput = 500;
t = 1:Linput;
mTT = rand(N,1);
alf = rand(N,1);
beta = mTT./alf;
faktor = 1./(beta.^alf.*gamma(alf));
A = t.^(alf-1);
B = -t./beta ;
C = faktor.*A.*exp(B);
toc
Elapsed time is 104.574729 seconds. speed up with power function MATLAB Answers — New Questions
How to find the orientation of the entire platform by looking at the overall geometey of the objects/dots?
Hi, Im trying to find the orientation that is roll and pitch angle of my platform by analysing the overall geometery of the dots. To do so i have firstly detected the dots by using standard deviation and k-means clustering and dividing the image into 5×5 boxes then a plane fitting curve method is used to determine the overall geometery of the dots which further gives orientation of the plate. The obtained angles are incorrect what might have possibly gone wrong please help and suggest any possible solution. I’m actually trying to implement a blass on a plate system and i want to detect the orientation of the plate using webcam. Also im using MATLAB 2021a therefore im not sure how to calibrate my camera for such a pattern. The MATLAB code is given below;
clear all;
clc;
close all;
% Create a webcam object
cap = webcam(‘Adesso CyberTrack H3’);
% Adjust camera settings if supported
try
% Set the exposure time (shutter speed) in seconds
exposureTime = 0.01; % Adjust as needed
cap.ExposureMode = ‘manual’;
cap.Exposure = exposureTime;
catch ME
disp(‘Warning: Unable to set exposure time for the camera.’);
disp(ME.message);
end
% Create the background subtractor object for ball detection
back_sub = vision.ForegroundDetector(‘NumTrainingFrames’, 100, ‘NumGaussians’, 3, ‘MinimumBackgroundRatio’, 0.7);
% Create structuring element for morphological operation
se = strel(‘rectangle’, [20, 20]);
% Initialize calibration values
calibration_pitch = 0;
calibration_roll = 0;
% Calibrate the system to set initial pitch and roll to zero
frame = snapshot(cap);
I_gray = rgb2gray(frame);
I_contrast = imadjust(I_gray);
bw = imbinarize(I_contrast, ‘adaptive’);
bw_filled = imfill(bw, ‘holes’);
bw_cleaned = bwareaopen(bw_filled, 50);
stats = regionprops(‘table’, bw_cleaned, ‘Centroid’, ‘BoundingBox’);
centroids = stats.Centroid;
if size(centroids, 1) >= 3
X = centroids(:, 1);
Y = centroids(:, 2);
Z = linspace(0, 1, size(centroids, 1))’;
A = [X, Y, ones(size(X))];
coeffs = A Z;
normal = [-coeffs(1), -coeffs(2), 1];
normal = normal / norm(normal);
calibration_pitch = asin(normal(1));
calibration_roll = asin(normal(2));
disp([‘Calibration Pitch: ‘, num2str(calibration_pitch), ‘ degrees’]);
disp([‘Calibration Roll: ‘, num2str(calibration_roll), ‘ degrees’]);
else
disp(‘Not enough dots detected for calibration.’);
end
while true
% Read frame from webcam
frame = snapshot(cap);
% Part 1: Dot Detection and Tilt Angle Calculation
I_gray = rgb2gray(frame);
I_contrast = imadjust(I_gray);
bw = imbinarize(I_contrast, ‘adaptive’);
bw_filled = imfill(bw, ‘holes’);
bw_cleaned = bwareaopen(bw_filled, 50);
stats = regionprops(‘table’, bw_cleaned, ‘Centroid’, ‘BoundingBox’);
centroids = stats.Centroid;
boundingBoxes = stats.BoundingBox;
if size(centroids, 1) >= 3
X = centroids(:, 1);
Y = centroids(:, 2);
Z = linspace(0, 1, size(centroids, 1))’;
A = [X, Y, ones(size(X))];
coeffs = A Z;
normal = [-coeffs(1), -coeffs(2), 1];
normal = normal / norm(normal);
pitch = asin(normal(1)) – calibration_pitch;
roll = asin(normal(2)) – calibration_roll;
yaw = 0;
disp([‘Pitch (Tilt around Y-axis): ‘, num2str(pitch), ‘ degrees’]);
disp([‘Roll (Tilt around X-axis): ‘, num2str(roll), ‘ degrees’]);
disp([‘Yaw (Rotation around Z-axis): ‘, num2str(yaw), ‘ degrees’]);
else
pitch = 0;
roll = 0;
yaw = 0;
disp(‘Not enough dots detected to fit a plane.’);
end
for i = 1:size(boundingBoxes, 1)
frame = insertShape(frame, ‘Rectangle’, boundingBoxes(i, :), ‘Color’, ‘g’, ‘LineWidth’, 2);
end
fg_mask = step(back_sub, frame);
fg_mask = imclose(fg_mask, se);
fg_mask = medfilt2(fg_mask, [5, 5]);
fg_mask = uint8(fg_mask) * 255;
[contours, ~] = bwlabel(fg_mask);
stats = regionprops(contours, ‘Area’, ‘BoundingBox’, ‘Centroid’);
if ~isempty(stats)
[~, max_index] = max([stats.Area]);
centroid = stats(max_index).Centroid;
boundingBox = stats(max_index).BoundingBox;
frame = insertShape(frame, ‘Rectangle’, boundingBox, ‘Color’, [0, 255, 0], ‘LineWidth’, 3);
text = [‘x: ‘, num2str(centroid(1)), ‘, y: ‘, num2str(centroid(2))];
frame = insertText(frame, [centroid(1) – 10, centroid(2) – 10], text, ‘FontSize’, 50, ‘TextColor’, [0, 255, 0]);
coordinates = [];
coordinates = [coordinates; centroid];
disp(coordinates);
end
frame = insertText(frame, [10, 10], [‘Pitch: ‘, num2str(pitch), ‘°’], ‘FontSize’, 18, ‘BoxColor’, ‘red’, ‘TextColor’, ‘white’);
frame = insertText(frame, [10, 40], [‘Roll: ‘, num2str(roll), ‘°’], ‘FontSize’, 18, ‘BoxColor’, ‘red’, ‘TextColor’, ‘white’);
frame = insertText(frame, [10, 70], [‘Yaw: ‘, num2str(yaw), ‘°’], ‘FontSize’, 18, ‘BoxColor’, ‘red’, ‘TextColor’, ‘white’);
imshow(frame);
pause(0.0001);
end
clear cap;Hi, Im trying to find the orientation that is roll and pitch angle of my platform by analysing the overall geometery of the dots. To do so i have firstly detected the dots by using standard deviation and k-means clustering and dividing the image into 5×5 boxes then a plane fitting curve method is used to determine the overall geometery of the dots which further gives orientation of the plate. The obtained angles are incorrect what might have possibly gone wrong please help and suggest any possible solution. I’m actually trying to implement a blass on a plate system and i want to detect the orientation of the plate using webcam. Also im using MATLAB 2021a therefore im not sure how to calibrate my camera for such a pattern. The MATLAB code is given below;
clear all;
clc;
close all;
% Create a webcam object
cap = webcam(‘Adesso CyberTrack H3’);
% Adjust camera settings if supported
try
% Set the exposure time (shutter speed) in seconds
exposureTime = 0.01; % Adjust as needed
cap.ExposureMode = ‘manual’;
cap.Exposure = exposureTime;
catch ME
disp(‘Warning: Unable to set exposure time for the camera.’);
disp(ME.message);
end
% Create the background subtractor object for ball detection
back_sub = vision.ForegroundDetector(‘NumTrainingFrames’, 100, ‘NumGaussians’, 3, ‘MinimumBackgroundRatio’, 0.7);
% Create structuring element for morphological operation
se = strel(‘rectangle’, [20, 20]);
% Initialize calibration values
calibration_pitch = 0;
calibration_roll = 0;
% Calibrate the system to set initial pitch and roll to zero
frame = snapshot(cap);
I_gray = rgb2gray(frame);
I_contrast = imadjust(I_gray);
bw = imbinarize(I_contrast, ‘adaptive’);
bw_filled = imfill(bw, ‘holes’);
bw_cleaned = bwareaopen(bw_filled, 50);
stats = regionprops(‘table’, bw_cleaned, ‘Centroid’, ‘BoundingBox’);
centroids = stats.Centroid;
if size(centroids, 1) >= 3
X = centroids(:, 1);
Y = centroids(:, 2);
Z = linspace(0, 1, size(centroids, 1))’;
A = [X, Y, ones(size(X))];
coeffs = A Z;
normal = [-coeffs(1), -coeffs(2), 1];
normal = normal / norm(normal);
calibration_pitch = asin(normal(1));
calibration_roll = asin(normal(2));
disp([‘Calibration Pitch: ‘, num2str(calibration_pitch), ‘ degrees’]);
disp([‘Calibration Roll: ‘, num2str(calibration_roll), ‘ degrees’]);
else
disp(‘Not enough dots detected for calibration.’);
end
while true
% Read frame from webcam
frame = snapshot(cap);
% Part 1: Dot Detection and Tilt Angle Calculation
I_gray = rgb2gray(frame);
I_contrast = imadjust(I_gray);
bw = imbinarize(I_contrast, ‘adaptive’);
bw_filled = imfill(bw, ‘holes’);
bw_cleaned = bwareaopen(bw_filled, 50);
stats = regionprops(‘table’, bw_cleaned, ‘Centroid’, ‘BoundingBox’);
centroids = stats.Centroid;
boundingBoxes = stats.BoundingBox;
if size(centroids, 1) >= 3
X = centroids(:, 1);
Y = centroids(:, 2);
Z = linspace(0, 1, size(centroids, 1))’;
A = [X, Y, ones(size(X))];
coeffs = A Z;
normal = [-coeffs(1), -coeffs(2), 1];
normal = normal / norm(normal);
pitch = asin(normal(1)) – calibration_pitch;
roll = asin(normal(2)) – calibration_roll;
yaw = 0;
disp([‘Pitch (Tilt around Y-axis): ‘, num2str(pitch), ‘ degrees’]);
disp([‘Roll (Tilt around X-axis): ‘, num2str(roll), ‘ degrees’]);
disp([‘Yaw (Rotation around Z-axis): ‘, num2str(yaw), ‘ degrees’]);
else
pitch = 0;
roll = 0;
yaw = 0;
disp(‘Not enough dots detected to fit a plane.’);
end
for i = 1:size(boundingBoxes, 1)
frame = insertShape(frame, ‘Rectangle’, boundingBoxes(i, :), ‘Color’, ‘g’, ‘LineWidth’, 2);
end
fg_mask = step(back_sub, frame);
fg_mask = imclose(fg_mask, se);
fg_mask = medfilt2(fg_mask, [5, 5]);
fg_mask = uint8(fg_mask) * 255;
[contours, ~] = bwlabel(fg_mask);
stats = regionprops(contours, ‘Area’, ‘BoundingBox’, ‘Centroid’);
if ~isempty(stats)
[~, max_index] = max([stats.Area]);
centroid = stats(max_index).Centroid;
boundingBox = stats(max_index).BoundingBox;
frame = insertShape(frame, ‘Rectangle’, boundingBox, ‘Color’, [0, 255, 0], ‘LineWidth’, 3);
text = [‘x: ‘, num2str(centroid(1)), ‘, y: ‘, num2str(centroid(2))];
frame = insertText(frame, [centroid(1) – 10, centroid(2) – 10], text, ‘FontSize’, 50, ‘TextColor’, [0, 255, 0]);
coordinates = [];
coordinates = [coordinates; centroid];
disp(coordinates);
end
frame = insertText(frame, [10, 10], [‘Pitch: ‘, num2str(pitch), ‘°’], ‘FontSize’, 18, ‘BoxColor’, ‘red’, ‘TextColor’, ‘white’);
frame = insertText(frame, [10, 40], [‘Roll: ‘, num2str(roll), ‘°’], ‘FontSize’, 18, ‘BoxColor’, ‘red’, ‘TextColor’, ‘white’);
frame = insertText(frame, [10, 70], [‘Yaw: ‘, num2str(yaw), ‘°’], ‘FontSize’, 18, ‘BoxColor’, ‘red’, ‘TextColor’, ‘white’);
imshow(frame);
pause(0.0001);
end
clear cap; Hi, Im trying to find the orientation that is roll and pitch angle of my platform by analysing the overall geometery of the dots. To do so i have firstly detected the dots by using standard deviation and k-means clustering and dividing the image into 5×5 boxes then a plane fitting curve method is used to determine the overall geometery of the dots which further gives orientation of the plate. The obtained angles are incorrect what might have possibly gone wrong please help and suggest any possible solution. I’m actually trying to implement a blass on a plate system and i want to detect the orientation of the plate using webcam. Also im using MATLAB 2021a therefore im not sure how to calibrate my camera for such a pattern. The MATLAB code is given below;
clear all;
clc;
close all;
% Create a webcam object
cap = webcam(‘Adesso CyberTrack H3’);
% Adjust camera settings if supported
try
% Set the exposure time (shutter speed) in seconds
exposureTime = 0.01; % Adjust as needed
cap.ExposureMode = ‘manual’;
cap.Exposure = exposureTime;
catch ME
disp(‘Warning: Unable to set exposure time for the camera.’);
disp(ME.message);
end
% Create the background subtractor object for ball detection
back_sub = vision.ForegroundDetector(‘NumTrainingFrames’, 100, ‘NumGaussians’, 3, ‘MinimumBackgroundRatio’, 0.7);
% Create structuring element for morphological operation
se = strel(‘rectangle’, [20, 20]);
% Initialize calibration values
calibration_pitch = 0;
calibration_roll = 0;
% Calibrate the system to set initial pitch and roll to zero
frame = snapshot(cap);
I_gray = rgb2gray(frame);
I_contrast = imadjust(I_gray);
bw = imbinarize(I_contrast, ‘adaptive’);
bw_filled = imfill(bw, ‘holes’);
bw_cleaned = bwareaopen(bw_filled, 50);
stats = regionprops(‘table’, bw_cleaned, ‘Centroid’, ‘BoundingBox’);
centroids = stats.Centroid;
if size(centroids, 1) >= 3
X = centroids(:, 1);
Y = centroids(:, 2);
Z = linspace(0, 1, size(centroids, 1))’;
A = [X, Y, ones(size(X))];
coeffs = A Z;
normal = [-coeffs(1), -coeffs(2), 1];
normal = normal / norm(normal);
calibration_pitch = asin(normal(1));
calibration_roll = asin(normal(2));
disp([‘Calibration Pitch: ‘, num2str(calibration_pitch), ‘ degrees’]);
disp([‘Calibration Roll: ‘, num2str(calibration_roll), ‘ degrees’]);
else
disp(‘Not enough dots detected for calibration.’);
end
while true
% Read frame from webcam
frame = snapshot(cap);
% Part 1: Dot Detection and Tilt Angle Calculation
I_gray = rgb2gray(frame);
I_contrast = imadjust(I_gray);
bw = imbinarize(I_contrast, ‘adaptive’);
bw_filled = imfill(bw, ‘holes’);
bw_cleaned = bwareaopen(bw_filled, 50);
stats = regionprops(‘table’, bw_cleaned, ‘Centroid’, ‘BoundingBox’);
centroids = stats.Centroid;
boundingBoxes = stats.BoundingBox;
if size(centroids, 1) >= 3
X = centroids(:, 1);
Y = centroids(:, 2);
Z = linspace(0, 1, size(centroids, 1))’;
A = [X, Y, ones(size(X))];
coeffs = A Z;
normal = [-coeffs(1), -coeffs(2), 1];
normal = normal / norm(normal);
pitch = asin(normal(1)) – calibration_pitch;
roll = asin(normal(2)) – calibration_roll;
yaw = 0;
disp([‘Pitch (Tilt around Y-axis): ‘, num2str(pitch), ‘ degrees’]);
disp([‘Roll (Tilt around X-axis): ‘, num2str(roll), ‘ degrees’]);
disp([‘Yaw (Rotation around Z-axis): ‘, num2str(yaw), ‘ degrees’]);
else
pitch = 0;
roll = 0;
yaw = 0;
disp(‘Not enough dots detected to fit a plane.’);
end
for i = 1:size(boundingBoxes, 1)
frame = insertShape(frame, ‘Rectangle’, boundingBoxes(i, :), ‘Color’, ‘g’, ‘LineWidth’, 2);
end
fg_mask = step(back_sub, frame);
fg_mask = imclose(fg_mask, se);
fg_mask = medfilt2(fg_mask, [5, 5]);
fg_mask = uint8(fg_mask) * 255;
[contours, ~] = bwlabel(fg_mask);
stats = regionprops(contours, ‘Area’, ‘BoundingBox’, ‘Centroid’);
if ~isempty(stats)
[~, max_index] = max([stats.Area]);
centroid = stats(max_index).Centroid;
boundingBox = stats(max_index).BoundingBox;
frame = insertShape(frame, ‘Rectangle’, boundingBox, ‘Color’, [0, 255, 0], ‘LineWidth’, 3);
text = [‘x: ‘, num2str(centroid(1)), ‘, y: ‘, num2str(centroid(2))];
frame = insertText(frame, [centroid(1) – 10, centroid(2) – 10], text, ‘FontSize’, 50, ‘TextColor’, [0, 255, 0]);
coordinates = [];
coordinates = [coordinates; centroid];
disp(coordinates);
end
frame = insertText(frame, [10, 10], [‘Pitch: ‘, num2str(pitch), ‘°’], ‘FontSize’, 18, ‘BoxColor’, ‘red’, ‘TextColor’, ‘white’);
frame = insertText(frame, [10, 40], [‘Roll: ‘, num2str(roll), ‘°’], ‘FontSize’, 18, ‘BoxColor’, ‘red’, ‘TextColor’, ‘white’);
frame = insertText(frame, [10, 70], [‘Yaw: ‘, num2str(yaw), ‘°’], ‘FontSize’, 18, ‘BoxColor’, ‘red’, ‘TextColor’, ‘white’);
imshow(frame);
pause(0.0001);
end
clear cap; matlab, image processing, computer vision MATLAB Answers — New Questions
How to generate a2l (asap2) file for Autosar classic platform with Matlab R2021b?
In Matlab R2021b, the method of generating a2l file is changed. But the new a2l generation tool named Generate Calibration Files suppors only targets like ert, grt and adaptive autosar. It does not support the classic Autosar target.
How to generate a2l (asap2) file for the classic autosar simulink models with Matlab R2021b?In Matlab R2021b, the method of generating a2l file is changed. But the new a2l generation tool named Generate Calibration Files suppors only targets like ert, grt and adaptive autosar. It does not support the classic Autosar target.
How to generate a2l (asap2) file for the classic autosar simulink models with Matlab R2021b? In Matlab R2021b, the method of generating a2l file is changed. But the new a2l generation tool named Generate Calibration Files suppors only targets like ert, grt and adaptive autosar. It does not support the classic Autosar target.
How to generate a2l (asap2) file for the classic autosar simulink models with Matlab R2021b? aspa2, a2l, simulink, r2021b, autosar, classic autosar MATLAB Answers — New Questions
Performance of ode solvers in Matlab and Simulink
I have implemented a simulation of a system with around 20k states in Simulink via a Matlab System using iterpreted execution (since I was lazy, I used simbolic variables in the setupImpl() function for deriving the stepImpl() function more easily). The model simulates rather slow, and thus I am thinking on what to do next to improve performance. I thought about
1) rewrite the matlab system such that I can use code generation for execution
2) use the obj.stepImpl() function in the workspace and call there an ode solver.
Do you have a guess which of the options is going to show better performance? Are there any advantages of both options? Option 2) would be much easier for me to implement.
Thanks in advance!I have implemented a simulation of a system with around 20k states in Simulink via a Matlab System using iterpreted execution (since I was lazy, I used simbolic variables in the setupImpl() function for deriving the stepImpl() function more easily). The model simulates rather slow, and thus I am thinking on what to do next to improve performance. I thought about
1) rewrite the matlab system such that I can use code generation for execution
2) use the obj.stepImpl() function in the workspace and call there an ode solver.
Do you have a guess which of the options is going to show better performance? Are there any advantages of both options? Option 2) would be much easier for me to implement.
Thanks in advance! I have implemented a simulation of a system with around 20k states in Simulink via a Matlab System using iterpreted execution (since I was lazy, I used simbolic variables in the setupImpl() function for deriving the stepImpl() function more easily). The model simulates rather slow, and thus I am thinking on what to do next to improve performance. I thought about
1) rewrite the matlab system such that I can use code generation for execution
2) use the obj.stepImpl() function in the workspace and call there an ode solver.
Do you have a guess which of the options is going to show better performance? Are there any advantages of both options? Option 2) would be much easier for me to implement.
Thanks in advance! ode, simulink, performance, code generation, interpreted execution, matlab system MATLAB Answers — New Questions
Plotting Discrete Time Functions
I need to plot 5 cos(π n /6 – π/2) as a discrete tim signal. But I am not getting the proper result.
n = [-5:0.001:5];
y = 5*cos(pi*(n/2)-(pi/2));
stem(n,y);
What am I missing from this code to get the discrete time signals?I need to plot 5 cos(π n /6 – π/2) as a discrete tim signal. But I am not getting the proper result.
n = [-5:0.001:5];
y = 5*cos(pi*(n/2)-(pi/2));
stem(n,y);
What am I missing from this code to get the discrete time signals? I need to plot 5 cos(π n /6 – π/2) as a discrete tim signal. But I am not getting the proper result.
n = [-5:0.001:5];
y = 5*cos(pi*(n/2)-(pi/2));
stem(n,y);
What am I missing from this code to get the discrete time signals? discrete time signals, functions MATLAB Answers — New Questions
Error occurred while executing the listener callback for event DataWritten defined for class asyncio.InputStream
Hi,
I am reading data over TCP/IP from hardware device using
t1=tcpclient("xxxx",xxxx)
I am configuring callback function, so that when ever 210 data byes avaible to read function1() execute.
while t1.BytesAvailable == 0
%wait for data
end
configureCallback(t1,"byte",210,@varargin()function1())
function function1()
Bytes_DATAF1=t1.NumBytesAvailable
DATA=read(t1,210);
decode=swapbytes(typecast(uint8(DATAF1(1,7:10)’),’uint32′));
Bytes_DATAF2=t1.NumBytesAvailable
end
codes doing fine but in middle giving following warning.
Warning: Error occurred while executing the listener callback for event DataWritten
defined for class asyncio.InputStream:
Error using +
Integers can only be combined with integers of the same class, or scalar doubles.
Error in matlabshared.network.internal.TCPClient/onDataReceived
Error in
matlabshared.network.internal.TCPClient>@(varargin)obj.onDataReceived(varargin{:})
Error in asyncio.Channel/onDataReceived (line 487)
notify(obj.InputStream, ‘DataWritten’, …
Error in asyncio.Channel>@(source,data)obj.onDataReceived() (line 425)
@(source, data) obj.onDataReceived());
> In asyncio/Channel/onDataReceived (line 487)
In asyncio.Channel>@(source,data)obj.onDataReceived() (line 425)
——————————————————————————————————–
function function1()
Bytes_DATAF1=t1.NumBytesAvailable
DATA=read(t1,210);
decode=swapbytes(typecast(uint8(DATAF1(1,7:10)’),’uint32′));
Bytes_DATAF2=t1.NumBytesAvailable
end
bytes availabe to read
t1.BytesAvailable=Bytes_DATAF1 =12810
mycode reads only 210 bytes
bytes remaining to read
t1.BytesAvailable=Bytes_DATAF2 = 255
12810-255=12555 bytes missing.Hi,
I am reading data over TCP/IP from hardware device using
t1=tcpclient("xxxx",xxxx)
I am configuring callback function, so that when ever 210 data byes avaible to read function1() execute.
while t1.BytesAvailable == 0
%wait for data
end
configureCallback(t1,"byte",210,@varargin()function1())
function function1()
Bytes_DATAF1=t1.NumBytesAvailable
DATA=read(t1,210);
decode=swapbytes(typecast(uint8(DATAF1(1,7:10)’),’uint32′));
Bytes_DATAF2=t1.NumBytesAvailable
end
codes doing fine but in middle giving following warning.
Warning: Error occurred while executing the listener callback for event DataWritten
defined for class asyncio.InputStream:
Error using +
Integers can only be combined with integers of the same class, or scalar doubles.
Error in matlabshared.network.internal.TCPClient/onDataReceived
Error in
matlabshared.network.internal.TCPClient>@(varargin)obj.onDataReceived(varargin{:})
Error in asyncio.Channel/onDataReceived (line 487)
notify(obj.InputStream, ‘DataWritten’, …
Error in asyncio.Channel>@(source,data)obj.onDataReceived() (line 425)
@(source, data) obj.onDataReceived());
> In asyncio/Channel/onDataReceived (line 487)
In asyncio.Channel>@(source,data)obj.onDataReceived() (line 425)
——————————————————————————————————–
function function1()
Bytes_DATAF1=t1.NumBytesAvailable
DATA=read(t1,210);
decode=swapbytes(typecast(uint8(DATAF1(1,7:10)’),’uint32′));
Bytes_DATAF2=t1.NumBytesAvailable
end
bytes availabe to read
t1.BytesAvailable=Bytes_DATAF1 =12810
mycode reads only 210 bytes
bytes remaining to read
t1.BytesAvailable=Bytes_DATAF2 = 255
12810-255=12555 bytes missing. Hi,
I am reading data over TCP/IP from hardware device using
t1=tcpclient("xxxx",xxxx)
I am configuring callback function, so that when ever 210 data byes avaible to read function1() execute.
while t1.BytesAvailable == 0
%wait for data
end
configureCallback(t1,"byte",210,@varargin()function1())
function function1()
Bytes_DATAF1=t1.NumBytesAvailable
DATA=read(t1,210);
decode=swapbytes(typecast(uint8(DATAF1(1,7:10)’),’uint32′));
Bytes_DATAF2=t1.NumBytesAvailable
end
codes doing fine but in middle giving following warning.
Warning: Error occurred while executing the listener callback for event DataWritten
defined for class asyncio.InputStream:
Error using +
Integers can only be combined with integers of the same class, or scalar doubles.
Error in matlabshared.network.internal.TCPClient/onDataReceived
Error in
matlabshared.network.internal.TCPClient>@(varargin)obj.onDataReceived(varargin{:})
Error in asyncio.Channel/onDataReceived (line 487)
notify(obj.InputStream, ‘DataWritten’, …
Error in asyncio.Channel>@(source,data)obj.onDataReceived() (line 425)
@(source, data) obj.onDataReceived());
> In asyncio/Channel/onDataReceived (line 487)
In asyncio.Channel>@(source,data)obj.onDataReceived() (line 425)
——————————————————————————————————–
function function1()
Bytes_DATAF1=t1.NumBytesAvailable
DATA=read(t1,210);
decode=swapbytes(typecast(uint8(DATAF1(1,7:10)’),’uint32′));
Bytes_DATAF2=t1.NumBytesAvailable
end
bytes availabe to read
t1.BytesAvailable=Bytes_DATAF1 =12810
mycode reads only 210 bytes
bytes remaining to read
t1.BytesAvailable=Bytes_DATAF2 = 255
12810-255=12555 bytes missing. tcpclient, callback, configurecallback MATLAB Answers — New Questions
What principles does the accumulator for storing data (output or intermediate) follow after converting the model into C code using a C coder?
For example, is the upper limit of i in the for loop automatically generated based on factors such as the size of the data or something else?I would like to interrupt the process of generating data into smaller segments as per my request, but I don’t know how to handle these data or intermediate quantities because I am concerned that interrupting this process directly may lead to uncontrollable issues such as data leakage or data coverage。For example, is the upper limit of i in the for loop automatically generated based on factors such as the size of the data or something else?I would like to interrupt the process of generating data into smaller segments as per my request, but I don’t know how to handle these data or intermediate quantities because I am concerned that interrupting this process directly may lead to uncontrollable issues such as data leakage or data coverage。 For example, is the upper limit of i in the for loop automatically generated based on factors such as the size of the data or something else?I would like to interrupt the process of generating data into smaller segments as per my request, but I don’t know how to handle these data or intermediate quantities because I am concerned that interrupting this process directly may lead to uncontrollable issues such as data leakage or data coverage。 simulink, signal MATLAB Answers — New Questions