Increasing of speed in numerical calculation
6 次查看(过去 30 天)
显示 更早的评论
Hello,
I'm writing my master thesis about the implementation of a Monte Carlo approach (numerical calculation) in Matlab R2011b. The program needs to much computation time so I want to increase the speed.
My program generates random values for different input variables and evaluates a calculation model to get the values of the output variables (eg a+b=c).This calculation must be carried out approximately 10^6 times in order to provide reasonable results.
I was thinking of converting the random values from double into string followed by replacing the strings of the variables in the model with the strings of the values (by using 'strrep'). Finally the equation should be calculated by the command 'eval'. This procedure has to be repeated for 10^6 times, so it takes unfortunatelly very long time.
My idea was using mex functions for the implemenation of the loops to reduce the computation time. My problem is the transfer and the calculation of vectors and matrices in the mex-function.
Does anyone has a clue of programming with mex-functions or is there possibly another way to increase the speed of large for-loops?
Thank you very much!
2 个评论
Richard Brown
2012-4-29
Why do you need to go to strings and back? Why can't you evaluate the expression directly with the randomly generated values?
Jan
2012-4-30
Cross posting confuses the ones, who want to assist. Please add a link to your question, if you post a question in other forums also.
回答(6 个)
per isakson
2012-4-29
I tried to edit my answer and clicked the wrong button and it was gone.
--- New answer ---
Here is a small demo of
- writing code to a file
- making a function_handle
- executing the code
During development of the code it is useful to leave the file on the HD so that it can be inspected. The string, frmt, may be large.
frmt = 'function output = %s( input )\noutput = %u%sinput;\nend';
function_name = 'on_the_fly';
tic
fid = fopen( [function_name,'.m'], 'w+' );
fprintf( fid, frmt, function_name, 3, '*' );
fclose( fid );
toc
fh = str2func( function_name );
disp( fh( 17 ) )
Running this script displays:
Elapsed time is 0.005069 seconds.
51
The m-file looks like this
function output = on_the_fly( input )
output = 3*input;
end
The alternative is to use EVAL.
Evaluate the alternatives with the profiler.
0 个评论
per isakson
2012-5-2
Something like this
f( varargin{:} )
where
varargin == {x,y,z}
assuming the value of varargin is set in a call of the function (which function?).
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Numeric Types 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!