MATLAB: Using function from a separate file

function from fileMATLAB

Hello,
How can I return a function from a function from file. For example:
.m
function f = squareAndDiff(x)
f = diff(x*x);
end
test.m
fminbnd(@squareAndDiff,0,10)
Error occurs saying:
"user supplied objective function must return a scalar value"
What does this mean and how can I fix it?
Thanks

Best Answer

From the way you constructed your ‘squareAndDiff’ function, ‘x’ is a scalar (otherwise the ‘f’ assignment would throw an error) so the diff of a scalar will return an empty array:
q = diff(5)
returns:
q =
[]
which is not a scalar value.
Since I am not sure that I understand what you want to do, I can’t suggest a fix.
However, for diff to return a scalar, the argument must be a 2-element vector.