How to fix this code
2 views (last 30 days)
Show older comments
function [Centriod, M_Inertia,cpmo]=Rect(x,y)
if ~isequal(size(x),size(y))
error('X and Y must be the same size');
end
xm=mean(x);
ym=mean(y);
x=x-xm;
y=y-ym;
xp=x([2:end 1]);
yp=y([2:end 1]);
a=x.*yp-xp.*y;
A=sum(a)/2;
xc=sum((x+xp).*a)/6/A;
yc=sum((y+yp).*a)/6/A;
Ixx=sum((y.*y+y.*yp+yp.*yp).*a)/12;
Iyy=sum((x.*x+x.*xp+xp.*xp).*a)/12;
Ixy=sum((x.*yp+2*x.*y+2*xp.*yp+xp.*y).*a)/24;
dx=xp-x;
dy=yp-y;
P=sum(sqrt(dx.*dx+dy.*dy));
if A<0
A=-A;
Ixx=-Ixx;
Iyy=-Iyy;
Ixy=-Ixy;
end
Iuu=Ixx-A*yc*yc;
Ivv=Iyy-A*xc*xc;
Iuv=Ixy-A*xc*yc;
J=Iuu+Ivv;
x_cen=xc+xm;
y_cen=yc+ym;
Ixx=Iuu+A*y_cen*y_cen;
Iyy=Ivv+A*x_cen*x_cen;
Ixy=Iuv+A*x_cen*y_cen;
I=[Iuu -Ivv;
-Iuv Ivv];
[eig_vec, eig_val]=eig(I);
I1=eig_val(1,1);
I2=eig_val(2,2);
ang1=atan2(eig_vec(2,1),eig_vec(1,1));
ang2=atan2(eig_vec(2,2),eig_vec(1,2));
Centriod=[A x_cen y_cen P];
M_Inertia=[Ixx Iyy Ixy];
cpmo=[I1 ang1 I2 ang2 J];
end
Error using eig
Input to EIG must not contain NaN or Inf.
Error in Rect (line 46)
[eig_vec, eig_val]=eig(I);
0 Comments
Answers (1)
Aquatris
on 20 Jul 2018
Edited: Aquatris
on 20 Jul 2018
In these lines;
xc=sum((x+xp).*a)/6/A
yc=sum((y+yp).*a)/6/A
when A is 0, these values become NaN since division by 0 is not defined. Since they are NaN, any other variable that uses them become NaN as well. eig() function requires numeric values since there cannot be eigenvalues of NaN.
If in your application A can be 0, these equations do not seem to be right. Otherwise, if A can be 0 and the equations are right, you can use an if statement to force xc and yc to be some number when A is equal to 0.
4 Comments
Aquatris
on 20 Jul 2018
Correct but the underlying reason is the variable A. Since A is NaN, the other variables that are calculated using the A variable becomes NaN as well. Then you feed a matrix with NaN elements to eig() function, which is where you see the error since eig() function cannot work with NaN.
To test this, you can replace the equation that is "A = sum(a)/2" withs "A = 5" or any other numeric value, and you will see your code runs fine.
See Also
Categories
Find more on Linear Algebra in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!