Question

I have a script that calls itself over when the condition of the if-statement is false. The maximum number of iterations as defined by the user can be up to 20 times.

The problem is that there is a variable(s) that changes inside the algorithm itself, and if the condition of the if-statement is false, the whole process will start over. The thing is that the new calculations to be made when it starts again should depend on the last calculated value and not the initial one. At this point, I am achieving what I want by using set-get functions. The issue with the set-value criteria is that it updates the GUI in every run, and this is very time consuming. Any ideas are much appreciated. Below is the code which works, but lengthy; kindly note that this is a very short summary of the actual script but it serves the purpose.

FunctionOne
       InitialPrice=str2double(get(handles.StockP,'String'));
       TargetPrice=105;
       T=str2double(get(handles.Time,'String')); %This value is maximum 20 
       StockPrice= InitialPrice*(1+randn) %just for simplicity
       If Time > 0 
            If StockPrice>TargetPrice 
              update the GUI %end
            else 
               set(handles.StockP,(StockPrice))
               set(handles.Time,'String',(T-1))
               FunctionOne  
            end
        end
end
Was it helpful?

Solution

Can you have FunctionOne take arguments as below? When calling from inside FunctionOne, you pass two arguments, but when calling the function from outside, you call it without arguments like you were doing before.

FunctionOne (StockP,Time)

   if nargin == 2
       InitialPrice = StockP;
       T = Time;
   else 
       InitialPrice=str2double(get(handles.StockP,'String'));
       T=str2double(get(handles.Time,'String')); %This value is maximum 20 
   end

   TargetPrice=105;
   StockPrice= InitialPrice*(1+randn) %just for simplicity

   If T > 0 
        If StockPrice>TargetPrice 
          update the GUI %end
        else 
           FunctionOne(StockPrice,T-1); 
        end
    end
end

OTHER TIPS

Perhaps you could store StockPrice in a global array, remove the recursive calls and only update the GUI after all your calculation steps have completed. Something like:

FunctionOne(InitialPrice, TargetPrice, Time)
    StockPrice(1) = InitialPrice;
    T = ...;
    i = 1;

    while( T>0 )
        i = i+1;
        T = T-1;
        StockPrice(i) = StockPrice(i-1)*(1+randn);
    end

    Update the GUI %not sure if you want to only use certain StockPrice values or all of them
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top