I am new to matlab.
I am going to find the minimun value give the function: x(1)^2 - 2*x(1)*x(2) + 6*x(1) + x(2)^2 - 6*x(2)
I am trying to write the matlab code without using the anonymous function, but I am stuck here now.
Here is my code:
function minFun()
res = fminsearch(@f2, [0,0]);
function out = f2([x(1) x(2)])
out = x(1)^2 - 2*x(1)*x(2) + 6*x(1) + x(2)^2 - 6*x(2);
end
end
But it mentions that here is syntax error in function out = f2([x(1) x(2)])
. How should I fix that?
If I understand you correctly you have 2 files. In your f2.m
file you should use
function out = f2(x)
out = x(1)^2 - 2*x(1)*x(2) + 6*x(1) + x(2)^2 - 6*x(2);
The input x
is already a vector.
If there is only one file then this should be the syntax:
function minFun()
res = fminsearch(@f2, [0,0])
function out = f2(x)
out = x(1)^2 - 2*x(1)*x(2) + 6*x(1) + x(2)^2 - 6*x(2);
note that I left res
without ;
so you can see the output of the fminsearch
.
尝试功能out = f2(x(1),x(2))
Note that matlab Anonymous functions are called with the @
operator, so your question is a little confusing, as your code try to use it.
function out = f2([x(1) x(2)])
This line is incorrect, you should use a variable as function argument x
.
If you do not want to use Anonymous function you should have a f2.m
file in your working directory or in matlab path, as the other answer says.
function out = f2(x)
out = x(1)^2 - 2*x(1)*x(2) + 6*x(1) + x(2)^2 - 6*x(2);
Then you reference the function with a string:
function minFun()
res = fminsearch('f2', [0,0]);
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.