fminsearch with vector function and vector output

7 views (last 30 days)
Hello, Sorry I think the question is trivial but I can't find any answers on the previous posts.
I have a function ' f ' that depends on a vector ' a ' :
a = 1:1000;
f = @(x) (x-a).^2;
and I want to get the minimum of this function for each value of ' a '. Ideally I thought a simple code like
x = fminsearch(f,1);
would generate a vector 'x' of solutions : x = [1 2 3 4 ...]. But fminsearch only works with scalars.
Any idea how to solve this? Thanks

Accepted Answer

Walter Roberson
Walter Roberson on 26 Oct 2016
x = arrayfun( @(v) fminsearch(@(x) (x-v).^2, 1), a );

More Answers (1)

Bjorn Gustavsson
Bjorn Gustavsson on 26 Oct 2016
For that function it is rather trivial, so you wouldn't need numerical methods.
For a more general function f(x,a) it might become significantly more problematic. The basic principle of the fminsearch function - cunningly walking around in the variable-space for x looking for lower values of your scalar function requires that the function returns scalar values.
In your case you'd have to do the numerical optimization in sequence for each value of a.
HTH
  1 Comment
Chang seok Ma
Chang seok Ma on 3 Nov 2021
Hello, I know this is a post five years ago, but I have one question about your answer.
I have seen couple of posts that vectorized fminsearch is not recommended but I don't still get why is it.
For example, if I want to solve the following
Y = x^2 + 2*x + 1
Y = x^2 + 4*x + 4
Y = x^2 + 6*x + 9
Y = x^2 + 8*x + 16
...
Y = x^2 + 200*x + 10000
and I want to get (-1, -2, -3, -4, ...,-100) as return.
I think it would be a problem if I want to solve something like
Y = f(x1,x2,x3,...,x30) (multiple choice variables) with vectorized fminsearch.
However, in the example code that I wrote, I thought I am just solving 100 different equations at the same time so using vector as an input for fminsearch shouldn't be a problem because this is just repeating scalarized fminsearch 100 times...
Am I understanding something wrong?

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!