How to change my equation in an interval to use fminsearch
조회 수: 8 (최근 30일)
이전 댓글 표시
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
John D'Errico
2020년 6월 12일
What is your question? What you have explained makes little sense.
That is, what does this mean:
from [a,b] is
eq = B(1)*k1 + B(2)*k2*x
from[b,c]
eq = B(1) + B(2)*x +k3
Are you saying you have a function that is piecewise linear, with two different straight lines that would be continuous at the joint point? So you have one line on the interval [a,b], and a second line on the interval [b,c]?
The code you wrote is not correct of course, but even at that, fminsearch is meaningless as you are trying to use it.
If all you have is a vector x, then how would you hope to choose the coefficients in that equation? You cannot create a line without both x and y. All you seem to have so far is x.
채택된 답변
Michael Soskind
2020년 6월 12일
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
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Particle & Nuclear Physics에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!