MATLAB: Error: Matrix dimensions must agree

MATLABmatrix array

Hi, I've got a function that I'm trying to define, it works for n=0 and n=1 but when I run it for n=2 I keep getting the error matrix dimensions must agree, i cant see what im doing wrong so any help would be great
The question i was given asked me to evaluate a function, and make sure it was adptable so that if it receives vectors of x and y it returns z as a 2D array.
function z = F(n,x,y)
% F Write a comment here that summarises what the function does.
% Write your code for the "F" function here.
[X,Y] = meshgrid(x,y);
if n==0
z = ones(10);
elseif n==1
z = (0.5.*X)-Y.^2;
else
z = 2.*n.*X.*Y.*F((n-1),X,Y)-((2.*n)+1).*F((n-2),X,Y);
z = z./(2.*n.^2);
end
end

Best Answer

I guess this is what you want. I have changed the input argument to the recursive function calls
function z = F(n,x,y)
% F Write a comment here that summarises what the function does.
% Write your code for the "F" function here.
[X,Y] = meshgrid(x,y);
if n==0
z = ones(size(X));
elseif n==1
z = (0.5.*X)-Y.^2;
else
z = 2.*n.*X.*Y.*F((n-1),x,y)-((2.*n)+1).*F((n-2),x,y);
z = z./(2.*n.^2);
end
end
Result:
>> F(3, 1:5, 1:5)
ans =
1.0e+03 *
-0.0001 -0.0004 -0.0001 0.0014 0.0046
-0.0014 -0.0077 -0.0153 -0.0222 -0.0265
-0.0101 -0.0461 -0.1002 -0.1678 -0.2443
-0.0361 -0.1558 -0.3449 -0.5952 -0.8989
-0.0936 -0.3927 -0.8752 -1.5286 -2.3402