0

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?

0

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Try function out = f2(x(1),x(2))

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.