'Error using - Matrix dimensions must agree.' Using anonymous functions

1 view (last 30 days)
I'm having some issues using anonymous functions, giving the error message 'Error using - Matrix dimensions must agree.' Code given below. R3 is a 3x1 vector, and all other variables not defined below are scalars.
f=1/(1+p^2+q^2)*[1-p^2+q^2 2*p*q -2*p]';
g=1/(1+p^2+q^2)*[2*p*q 1+p^2-q^2 2*q]';
X=@(F) a*((1-h^2*b)*cos(F)+h*k*b*sin(F)-k);
Y=@(F) a*((1-k^2*b)*sin(F)+h*k*b*cos(F)-h);
r=@(F) f*X(F)+g*Y(F);
dX=@(F) n*a^2/norm(r(F))*(h*k*b*cos(F)-(1-h^2*b*sin(F)));
dY=@(F) n*a^2/norm(r(F))*(-h*k*b*sin(F)+(1-k^2*b*cos(F)));
v=@(F) f*dX(F)+g*dY(F);
%Error is detected on this line
D=@(F) (r(F)-R3)*Cr*As*SF*Rs^2/(2*m*c*norm(r(F)-R3)^3);
da=@(F) 2*v(F)/(n^2*a);
symCja=@(F) 1/pi*dot(da(F),D(F))*cos(j*F);
Cj(1)=integral(symCja,-180,180);
I've tried calculating D using explicit values for F and it tells me that both r(F) and R3 are 3x1 vectors, so I don't see where the matrix dimensions issue comes from. I've also made sure that every other variable in that expression is a scalar, so I'm stumped- though my understanding of how anonymous functions actually work is very limited. Can anyone suggest where the issue might be coming from?

Accepted Answer

Matt J
Matt J on 29 Jun 2014
The function being integrated by the integral command must be able to accept a vector F as an input and return a vectorized result. Your D(F) cannot, and hence also symCja(F) which depends on it cannot.
  3 Comments
Matt J
Matt J on 29 Jun 2014
Edited: Matt J on 29 Jun 2014
I guess my understanding of this is incorrect then- are you saying that F MUST be a vector?
Your functions work fine when you pass scalar F to them, but the integral command requires them to support vector input as well. From the documentation for integral:
Integrand, specified as a function handle, defines the function to be integrated from xmin to xmax.For scalar-valued problems, the function y = fun(x) must accept a vector argument, x, and return a vector result, y.
In other words, integral is trying to pass batches of points F as a vector to be evaluated by symCja and is expecting a similar vector as output.
Matt J
Matt J on 29 Jun 2014
You could also solve the problem by calling integral as follows
Cj(1)=integral(symCja,-180,180,'ArrayValued',true)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!