nav-left cat-right
Matthias Pospiech > Programming > matlab > fast calculation of functions with two variables

fast calculation of functions with two variables

If you come from the programming world of C/C++ or java or any other traditional programming languages you might fall into the trap of using for loops for the calculation of functions. This works as expected but it is much slower than what matlab can do. The following example demonstrates this principle (which you should not use if you can)

Data2D = zeros([xPoints yPoints]);
for xi = 1:xPoints
    x = xAxis(xi);
    for yi = 1:yPoints        
        y = yAxis(yi);
        Data2D(xi,yi) = Ripple(x, y);

On my computer it takes 10.3 seconds for 1.000.000 datapoints.

If the function depends on a single variable one should use a vector and for two variables one should use matrices instead. The following example demonstrates how to calculate a functions with two variables in a single step:

xMat = (xAxis' * ones([1 yPoints]))';
yMat = yAxis' * ones([1 xPoints]);
Data2D = Ripple(xMat, yMat);

On my computer it takes 0.12 seconds for 1.000.000 datapoints, which is approx 90 times faster.

This is the complete code that was used

% clear command window, figures and all variables
clc; clf; clear all; 
%% Definition of calculation constants
% calculation of axis
xMax = 15;
xPoints = 1000;
xAxis = linspace(-xMax, xMax, xPoints);
yMax = 12;
yPoints = 1000;
yAxis = linspace(-yMax, yMax, yPoints);
%% function, here inline since it is rather simple
Ripple = @(x,y) ( (cos(sqrt(x.*x+y.*y) + cos(sqrt(((x+.913*2*pi).*(x+.913*2*pi))+y.*y)) + cos(sqrt(((x-.913*2*pi).*(x-.913*2*pi))+(y.*y))))*4) );
%% Calculation
% calculate in single line (fastest method)
xMat = (xAxis' * ones([1 yPoints]))';
yMat = yAxis' * ones([1 xPoints]);
Data2D = Ripple(xMat, yMat);
display(['calculated ' num2str(xPoints*yPoints) ' datapoints in ' num2str(toc) ' seconds']);
Data2D = Data2D / max(max(Data2D)); % normalize

Einen Kommentar schreiben

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.


This blog is kept spam free by WP-SpamFree.