# How to change my equation in an interval to use fminsearch

6 views (last 30 days)
Alexandra C on 12 Jun 2020
Answered: Michael Soskind on 12 Jun 2020
Hi, i'm new in matlab and i want to write an equation call ''eq'' that change twice to find some variables (B(1) and B(2)) with fminsearch later. x is a vector
from [a,b] is
eq = B(1)*k1 + B(2)*k2*x
from[b,c]
eq = B(1) + B(2)*x +k3
I wrote this but it doent work:
function B = Eq(x0,k1,k2,k3)
[B,val] = fminsearch(@nestedfun,x0);
function eq = nestedfun(B)
if x >= b
eq = B(1).*k1 +B(2)*k2* x ;
else if x <= b
eq = B(1)+ B(2).*x +k3;
end
end
end
end
##### 2 CommentsShowHide 1 older comment
Alexandra C on 12 Jun 2020
hi , thanks for you answer.
First i want to know how to writte this equation in matlab :
from [a,b] is
eq = B(1)*k1 + B(2)*k2*x
from[b,c]
eq = B(1) + B(2)*x +k3
is it this ? :
function eq = nestedfun(B)
if x >= b
eq = B(1).*k1 +B(2)*k2* x ;
else if x <= b
eq = B(1)+ B(2).*x +k3;
end
end
end

Michael Soskind on 12 Jun 2020
In general, I would advise using a different method for constructing the function. This would be to index the range of x. This means that you will use boolean inputs to a variable to select particular values of a variable.
%% Suppose you have the following values for r = [a,b,c], B = [B(1),B(2)], and k = [k(1),k(2),k(3)]
r = [-1,1,3];
B = [1,-2];
k = [1,2,3];
% plotting what the function looks like over the defined range of x
x = -10:3;
figure();
plot(x,Eq(x, B, r, k))
% Defining the function as a function of x as needed for fminsearch input
x0 = 0; % initial guess for fminsearch
[B,val] = fminsearch(@(x) Eq(x, r, B, k),x0);
% Function definition at end of program
function eq = Eq(x, r, B, k)
eq_1 = B(1).*k(1) + B(2)*k(2).* x(x <= r(2)); % selecting x values less than b
eq_2 = B(1) + B(2).*x(x > r(2)) + k(3); % selecting x values greater than b
eq = [eq_1,eq_2]; % combining the two sides of the piecewise function
end
It is additoinally important to understand how fminsearch works. It takes a function defined as a function of a parameter like x, and takes an initial guess (x0 above). Additionlly, the function only concatenates the two linear piecwise functions defined above, allowing for the function you seem to desire.
Hopefully that helps, and you learned something about how to index with Matlab (function) and also how to define a function of a variable. These will prove very useful for other even more complex functions as well.
Michael