开发者

How does MATLAB treat operations on subarrays in terms of speed and memory

I have large arrays which I am doing fairly simple linear algebra on. I have achieved good speed ups by vectorising the operations but i want to know how MATLAB treats the subarrays.

I pre-allocate arrays because they are used in various operations, and my formulae are long and require many different arrays and subarrays so readability counts while I am still coding.

For example, a simple case:

Array = someBig2DArray;
soln = Array;
[len_x len_y] = size(Array);
A1 = Array(2:len_x-1, 2:len_y-1);
A2 = Array(1:len_x-2, 2:len_y-1);
A3 = Array(3:len_x, 2:len_y-1);

soln(2:len_x-1, 2:len_y-1) = (A1 - 2*A2 + A3)/2 

The down side of using this method is that I have 3 extra arrays of basically the same size taking up memory.

Alternatively:

开发者_如何学编程
soln(2:len_x-1, 2:len_y-1) = (Array(3:len_x, 2:leny-1) - 2*Array(2:len_x-1, 2:len_y-1) + Array(1:len_x-2, 2:len_y-1))/2

Does this second method use less memory, while sacrificing readability? Or does it actually create 'temporary' arrays and actually end up using roughly the same amount of memory, but only briefly? (I am nearing the limit of my system...)

Are these methods the same speed internally, talking about bigO and number of operations?

Are there any ways of reducing the memory requirements of the first method while keeping readability?

Here is a snippit from my code (actually 1D in this case). My initial thinking was that vectorising the for loop and using matlab's usually very good matrix functions would speed things up. As it turns out the first method is significantly faster. Why?

for i = 3:len-1
    dSdx = sigma(i) - sigma(i-1) + ...
        0.25*(sigma(i+1) - sigma(i) - sigma(i-1) + sigma(i-2));
    ddSdx2 = sigma(i+1) - 2*sigma(i) + sigma(i-1);
    sigma_new(i) = sigma(i) + dT*(kappa*ddSdx2/h^2 - U*dSdx/h);
end

%This section replaces the for loop above
dSdx = sigma(3:len-1) - sigma(2:len-2) + 0.25*(sigma(4:len) ...
    - sigma(3:len-1) - sigma(2:len-2) + sigma(1:len-3));
ddSdx2 = sigma(4:len) - 2*sigma(3:len-1) + sigma(2:len-2);
sigma_new(3:len-1) = sigma(3:len-1) + dT*(kappa*ddSdx2/h^2 - U*dSdx/h);          


you can use tic and toc to time your methods. trying out your two approaches (there are some typos and assignment mismatches that needed to be fixed), shows that the second approach is ~3.5 times slower than the first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜