Search code examples
matlabfunction-handle

How can I fix the link between the multiplier and eqn(x)?


I am right now stuck on a problem in matlab. What I have done is that I have an equation that is passed on into another function which works by the bisection-method.

But I have a multiplier that I am trying to implement which somehow leads to the function crashing.

Before I introduced the multiplier it all worked, I tried breaking it down by entering the multiplier value manually and it didn't work

P_{1} = 0.6;
P_{2} = 0.2;
P_{3} = 0.2;
a_1 = 4/3;
a_2 = -7/3;
b_1 = -1/3;
b_2 = 4/3;
persistent multiplier
multiplier = exp(a_1 * 44 + a_2 * 14 + 0);
eqn = @(x) ((a_1 * x + b_1)^a_1) * ((a_2 * x + b_2)^a_2) * x ...
-(P_{1}^a_1) * (P_{2}^a_2) * P_{3} * multiplier; 
Q_{3} = Bisectionmethod(a_1, a_2, b_1, b_2, eqn);

Here is the calculating part of the bisection method.

x_lower = max(0, -b_1 / a_1);
x_upper = -b_2 / a_2;
x_mid = (x_lower + x_upper)/2;
Conditional statement encompassing the method of bisection
while abs(eqn(x_mid)) > 10^(-10)
if (eqn(x_mid) * eqn(x_upper)) < 0
    x_lower = x_mid;
else
    x_upper = x_mid;
end
x_mid = (x_lower + x_upper)/2;
end

Solution

  • Based on the information you provided this is what I came up with

    function Q = Stackoverflow
        persistent multiplier
    
        P{1} = 0.6;
        P{2} = 0.2;
        P{3} = 0.2;
        a1 = 4/3;
        a2 = -7/3;
        b1 = -1/3;
        b2 = 4/3;
    
        multiplier = exp(a1 * 44 + a2 * 14 + 0);
        eqn = @(x) ((a1 .* x + b1).^a1) .* ((a2 .* x + b2).^a2) .* x -(P{1}.^a1) .* (P{2}.^a2) .* P{3} .* multiplier; 
        Q{3} = Bisectionmethod(eqn, max([0, -b1/a1]), -b2/a2, 1E-10);
    end
    
    function XOut = Bisectionmethod(f, xL, xH, EPS)
        if sign(f(xL)) == sign(f(xH))
            XOut = [];
            error('Cannot bisect interval because can''t ensure the function crosses 0.')
        end
    
        x = [xL, xH];
    
        while abs(diff(x)) > EPS
            x(sign(f(mean(x))) == sign(f(x))) = mean(x);
        end
    
        XOut = mean(x);
    end