How to optmized for loop

Home Forums Matlab How to optmized for loop

This topic contains 1 reply, has 2 voices, and was last updated by  cK 9 years, 9 months ago.

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #504

    pankaj kumar
    Participant

    I have a vector “dd” having 25,000 element ,for which I like to check some property using heviside function as below but it goes out of memory. May I know any way to optimized the following code.

    for i = 1:25000
    for j = 1:25000
    M(i,j)=heaviside(0.1-sqrt(abs(dd(i)-dd(j))));
    end
    end

    #511

    cK
    Keymaster

    For this big calcs you need huge amounts of memory. This one would normally need 25e3 x 25e3 x 8bytes (double data) = 4.7GB just to store the variable. A computer with 8GB memory will likely pull it off. But if precision can be traded off, you halve the above memory requirement by using single data rather than double. Initialise M as
    M(25e3,25e3) = single(0);

    Then, you may speed up by vectorising the calculations. Use only one loop and compute the formula for each row at a time as
    M(:,j) = heaviside(0.1-sqrt(abs(dd-dd(j))));

    • This reply was modified 9 years, 9 months ago by  cK.
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.