Simulation of a function with loops

Dear All,
I have a script that calculates a stock price. It has multiple loops inside that can go up to 250 and it is fine, but if I increase the number to say 350, I get recursion break. This is okay since I don't need more than 180 as a maximum (half year).
The thing is that I want to simulate this model (large simulation, 1000000) to get valid results. I have tried to include a loop script which loops according to a defined number, but I get the recursion limit when I set the number of simulations to 50+. This is obvious as the model is consuming memory continuously.
Since it is not really practical to run 50 simulations every time, record the results and run again till I get large simulations, my problem becomes how to get about this in the best way; I need guidelines as I don't have much time left, otherwise I would go and try all possible solutions. Although I believe that it has to do with Simulink, not sure though about the process or whether this is achievable in Matlab or not. I am grateful for your suggestions that would assist me in getting what I am looking for.
Please refer to the first two comments for Per's answer below for the process and script.
I do really appreciate any help or suggestions provided.
Thanks & Best// Ali

댓글 수: 2

Jan
Jan 2013년 1월 5일
편집: Jan 2013년 1월 5일
What exactly is the question?
It should be a problem, when you set the 'String' property to a double value, e.g. in set(handles.St,'String',(101.6)). Then the number 101.6 is converted to a CHAR implicitly, such that char(101) is stored, which is an 'e'. Is this the wanted behavior?
AND
AND 2013년 1월 5일
Thanks Jan,
What exactly is the question?
The scenario is as follows: I have a function that loops inside to get a value. The function works fine and I am getting the required answer, and the question is how to apply large simulation to this function so I get large set of results.
It should be a problem, when you set the 'String' property to a double value, e.g. in set(handles.St,'String',(101.6)). Then the number 101.6 is converted to a CHAR implicitly, such that char(101) is stored, which is an 'e'. Is this the wanted behavior?
In my model, 101.6 is just an output of some calculations and the final result is correct.
I just need to know how to simulate this function.
Thanks again for your time// Ali

댓글을 달려면 로그인하십시오.

 채택된 답변

per isakson
per isakson 2013년 1월 5일

0 개 추천

  • with Matlab this is a script, not a function
  • I'm not sure I understand your question
  • the code doesn't explain why the recursion limit is reached. There is no recursion
  • setting the String-value of a uicontrol might take some time
Tentative answer:
  • convert the code to a function
  • call that function from another function, which contains the loop
Hint:
function some_output = pythia( )
some_output = zeros( zillion, 1 );
for ii = 1 : zillion
some_output(ii) = your_code( S, X, B, V, T, Tt )
end
end
function some_output = your_code( S, X, B, V, T, Tt )
FunctionOne;
St= S*(exp(randn));
if St<B
set(handles.St,'String',(0)) %set the value and exit
else
St=str2double( get(handles.St,'String')*exp(randn) );
if St<B
set(handles.St,'String',(0))
else
if tt<somecalculations
set(handles.St,'String',num2str(99.5)) %just an example
else
T=str2double( get(handles.T,'String') );
if T == 0
set(handles.St,'String', num2str(101.6) ) %just an example
else
set(handles.T,'String', num2str(T-1))
FunctionOne
end
end
end
end
end
function out = FunctionOne
out = 1;
end

댓글 수: 16

AND
AND 2013년 1월 5일
Dear Per, Many thanks for your detailed answer. I appreciate your time.
with Matlab this is a script, not a function
Yes actually it is indeed a script which I call upon clicking a button in a GUI. Now I can better explain my case.
setting the String-value of a uicontrol might take some time
Thanks, I am going to omit using setValue in the final script.
I'm not sure I understand your question
I have a GUI, where the user determines 11 variables. Upon clicking a button, a script runs and loops until it gets into one of four conditions (there is one variable 'N' that makes sure one of these four conditions is hit after it becomes 0). What I want is to simulate this script (like million times). I tried with normal if-loop script, but I get into the recursion limit in the 50 times. I would be thankful if you first inform me whether this is possible, and if yes how to achieve it; Simulink probably// any hints or guidelines are much appreciated.
As I couldn't put all words one time together, I am posting another comment.
Illustrated below is the case (the values are all retrieved from the GUI by 'str2double'); this is a clear summary of my exact code (any no closed form is due to type):
AND
AND 2013년 1월 5일
편집: AND 2013년 1월 5일
function pushbutton_Callback(hObject, eventdata, handles)
Function FirstFunction
MinimumInterval=Min(Intensity,exp(Jump))
Function SecondFunction %I created this function for GOTO purpose
Theta=log(StockP/ExcerciseP)
MinSI=Lambertw(MinSI) %Lambertw is the code for lambert code
caldel=min(TSmall-rvar,MinSI) %TSmall is important variable
NewStockPrice1= StockP*exp(somecalculations)
if NewStockPrice1 < Barrier
set the value of edittext and exit
else
TSmall = TPrime
if TSmall > TDelta
call SecondFunction
else
%some calculation here
if OneConditionisTrue
if Days==0;
set the value of edittext and exit
else
%some calculation here
if OneConditionisTrue
set the value of edittext and exit
else
NewDuration = Days - 1 %Here is where I make sure the script ends, for example if Days at the beginning is equal to 5 (LOOP), then, after hitting this loop 5 times, the script ends and gives a value as days==0.
TSmall = 1
FunctionOne
end
end
else
%Somecalculations
if Conditionismet
set the value of edittext and exit
else
Call FirstFunction (LOOP)
end
end
end
end
end
SecondFunction
end
FirstFunction
end
end
the code doesn't explain why the recursion limit is reached. There is no recursion
Maybe now, after submitting the script the recursion is shown!
per isakson
per isakson 2013년 1월 5일
편집: per isakson 2013년 1월 5일
what's the role of Simulink in your simulation?
AND
AND 2013년 1월 5일
what the role of Simulink in your simulation?
Thanks for your assistance Per. Actually, I am not sure, I just want to apply the simulations to my script in any possible way, and thought this could be done with Simulink as I have seen some examples but they are for simple functions. But first, do you think that I can simulate my script?
  • are FirstFunction and SecondFunction nested functions defined inside the callback function?
Function FirstFunction
...
Function SecondFunction %I created this function for GOTO purpose
per isakson
per isakson 2013년 1월 5일
편집: per isakson 2013년 1월 5일
No, I still don't understand why recursion occurs
Can't you define FirstFunction and SecondFunction in separate m-files?
AND
AND 2013년 1월 5일
편집: AND 2013년 1월 5일
Yes true, and the SecondFunction is defined inside the FirstFunction too.
Callback_Function
FirstFunction
SecondFunction
I try to have a minimum of code in callback_functions. The real work is done in separate functions. One gain two things: a separate function is easier to test and reuse. Thus,
function pushbutton_Callback(hObject, eventdata, handles)
...
results = separate_function( input, needed );
...
end
AND
AND 2013년 1월 5일
Many Thanks Per.
I was looking at the difference between scripts and functions just now, and the first advantage there functions are dynamic and you don't need to change the code when you want to change the input; since I am using GUI, I think that this advantage exists no more.
I can separate and create new functions, but not to deviate from my main issue, do you think I can apply large simulations to my model (now script later I can change to model)?
per isakson
per isakson 2013년 1월 5일
편집: per isakson 2013년 1월 5일
... simulate my script?
I see no reason why not. However, you might need to convert the script to a function. The word simulation mean slightly different things in different context. In the Matlab documentation there are demos and examples of, e.g. bootstrap and monte-carlo simulation, which just call an m-file function in a loop.
.
Yes true, and the SecondFunction is defined inside the FirstFunction too.
Do you have a good reason for that design? It seems a bit complicated. However, problems with the recursion limit may occur only if a function calls itself.
.
... difference between scripts and functions ...
IMO: there is hardly any place for scripts in production code. scripts in combination with "cell-mode"(%%) are handy to experiment with small algorithms, but that's about all.
AND
AND 2013년 1월 5일
Thanks Per,
This is exactly what I am looking for, MonteCarlo simulation of my model, but thought using the word 'simulation' only makes it clear. I had previously looked at the example provided by Matlab for MonteCarlo simulations, the problem is that these examples are totally different from my case. If I was looking to get the pattern the price follows or its stochastic process, I would be in a better shape and my problem would be solved. I will keep digging into the solution; meanwhile, any assistance is much appreciated.
You are right, but yes I need the function to call itself until there is an answer, and now I understand that this is causing the recursion limit call.
Thanks again for your time Per
per isakson
per isakson 2013년 1월 5일
편집: per isakson 2013년 1월 5일
'simulation' only makes it clear
I was confused by the "simulink" tag.
.
recursion limit
If you have 64bit and RAM enough I guess you can increase the limit. The alternative is to modify the code.
I'm a bit surprised by the random value in
St= S*(exp(randn));
I anticipate a approach like:
function [ consolidated, result ] = MySimulation( input, needed )
for loop
generate a clever set of stochastic input data
[ calculation, result ] = deterministic_function( input, data )
store calculation result
end
consolidate result
end
I was confused by the "simulink" tag.
:) That was a mistake, just corrected it.
If you have 64bit and RAM enough I guess you can increase the limit. The alternative is a code that converges quicker.
I have A8 QuadCorde 64bits with 8GB Rams, the problem is that if I increase the limit to 800+, Matlab crashes// if there was a way to overcome this - I wouldn't have had any problem at all.
I'm a bit surprised by the random value in
St= S*(exp(randn));
:D No, that was just an example :) - in the real code, one of the 3 different calculations for stock price is something like:
St= S*exp(randn*sigma*(sqrt(min(nvar,theta))-(0.5*(sigma^2)*min(nvar,theta))
I anticipate a approach like:
I will try this code but feels like exhausted :). I thought that I was done after I finished with the algorithm :).
One funny thing, I added another button now that call the main button callback
function pushbutton7_Callback(hObject, eventdata, handles)
pushbutton_Callback(hObject, eventdata, handles)
end
Now, if I call the function 3000 times, it is okay and I don't get any problems. Example, if N = 10, and I call the function 300 times such as:
function pushbutton7_Callback(hObject, eventdata, handles)
pushbutton_Callback(hObject, eventdata, handles)
pushbutton_Callback(hObject, eventdata, handles)
.....
.....
pushbutton_Callback(hObject, eventdata, handles) %(This is the 300)
end
I get no problems and get 3000 simulations; probably now I have to figure out how to call the function 300 times without repeating the name of the function 300x.
:)
AND
AND 2013년 1월 5일
Just figured it out through the for loop.
Thank you so much Per, shall I accept your answer so it is marked as solved?
Regards// Ali
AND
AND 2013년 1월 5일
Just a quick add that might be useful for others for future reference, I just added a for loop at the beginning of the script and it is now working :)// Thanks again Per, your contribution helped me get into the solution.
per isakson
per isakson 2013년 1월 5일
Ali
Perfect. I'm glad I could help. Please accept the answer and we regard this thread as closed. //per

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

AND
2013년 1월 5일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by