简体   繁体   English

Matlab查找无限制的最小值

[英]matlab find min value without constraint

I am new to matlab. 我是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) 我将找到赋予函数的最小值: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. 我试图在不使用匿名函数的情况下编写matlab代码,但是现在我被困在这里。

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)]) . 但是它提到这里是function out = f2([x(1) x(2)])语法错误。 How should I fix that? 我该如何解决?

If I understand you correctly you have 2 files. 如果我对您的理解正确,那么您有2个文件。 In your f2.m file you should use 在您的f2.m文件中,您应该使用

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. 输入x已经是一个向量。

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 ; 注意我没有留下res ; so you can see the output of the fminsearch . 这样您就可以看到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. 请注意,matlab匿名函数是使用@运算符调用的,因此您的问题有点令人困惑,因为您的代码尝试使用它。

function out = f2([x(1) x(2)])

This line is incorrect, you should use a variable as function argument x . 这行是不正确的,您应该使用变量作为函数参数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. 如果您不想使用匿名函数,则应该在工作目录或matlab路径中有一个f2.m文件,如另一个答案所述。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM