LMY
LMY

Reputation: 25

Use recursive MATLAB function or optimization?

I am trying to decide the most efficient, yet most precise approach to calculate a value called R which can only take a value between 0 and 1. Right now I have the below function used in the below script, but I feel like I am doing this in a non-optimal way. Currently I get an answer and have to feed that answer (again) as the initial "guess" in order to get the (next) most optimal answer. Could I build a better recursion for this or perhaps use one of Matlab's solvers? Thanks!

The function:

function f = Rfind(p,u,R)
    f = p .* (R.^u);
end

The script:

R = 0.999995753651217; % initial guess
matches = false;
while ~matches && R < 1
    R = R + 0.0000000000000000001; % increment R for next guess
    Jtotal = sum(Rfind(p,u,R)); % find R
    if abs(Jtotal - R)*10000000000 < 5 % check precision of result
        matches = true; % if R matches R fed to function, successful
    end
end
Jtotal

What I'm trying to identify:

Find a value of R equal to the sum of array p times R to the power of array u. Array p and array u both have the same number of elements, i.e. 12 rows in 1 column each. My function calculates R for each p and u row and then increments its guess to find the next closest match. It stops once the precision limit has been met or the input R and output total are identical.

Example Data:

Array p

0.00000693
0.00000231
0.00001386
0.00000924
0.00041360
0.00461657
0.03085337
0.01595235
0.09614154
0.06832660
0.11103563
0.67262800

Array u

50000
500
50
25
10
7.5
5
3.5
2.5
1.25
1
0

Important: I need the best precision for this but I don't want it taking 10 minutes like it has with extensions of the above.

Upvotes: 2

Views: 227

Answers (1)

EBH
EBH

Reputation: 10450

You can use fminbnd for this:

% first assign p and u
% define the function that you want to minimize:
Rfind = @(R) abs(sum(p.*(R.^u)) - R)
% set the tolerance to maximum:
options = optimset('TolX',eps); 
% find the value between 0 to 1 that minimize the function Rfind:
[R, err] = fminbnd(Rfind,0,1,options) 

and get (in a fraction of a second):

R =
   0.999995761369809
err =
     9.196743366857163e-11

Upvotes: 3

Related Questions