Path: news.mathworks.com!not-for-mail
From: "James Wright" <jameswright1001@yahoo.co.uk>
Newsgroups: comp.soft-sys.matlab
Subject: Help speeding up/replacing loops
Date: Tue, 16 Jun 2009 16:15:04 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 61
Message-ID: <h18ge7$gta$1@fred.mathworks.com>
Reply-To: "James Wright" <jameswright1001@yahoo.co.uk>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1245168904 17322 172.30.248.37 (16 Jun 2009 16:15:04 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Tue, 16 Jun 2009 16:15:04 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1878517
Xref: news.mathworks.com comp.soft-sys.matlab:547987


I've written some code, however it takes forever (several days) to run for larger values. Can anyone with more experience in matlab help me with the issue?? I understand vectorization is the way forward, but I'm unaware of how to do this for most of my loops.
Many thanks

Current Code:

function [] = the021testgraphnew(a1,an,aacc,x,N1,N2,g)
N = N1-N2;
ncut = N/10;
b = 0;
count = 0;
'creates the vector (1,2,...,ncut)';
X = 1:1:ncut;
'creates a vector with g random values';
C(1:g) = (rand(1)*pi);
'loops everything for each value of a (aka mu), this is time consuming but I cannot see another way around it';
for a = a1:aacc:an
    b = b + 1;
    A(b) = a;
    count = count + 1;
    'resets the expectation to 0';
    E = 0;
    'calculates the values of the transient';
    for j = 1:N2
        x = a*x*(1-x);
    end
    'calculates the values to actually be used and the expectation';
    for j = 1:N
        x = a*x*(1-x);
        B(j) = x;
        E = E + x;
    end
    E = E/N;
    'calculates the p''s and q''s';
    for f = 1:g
        p(1) = B(1)*cos(C(f));
        q(1) = B(1)*sin(C(f));
        for n = 2:N
                p(n) = p(n-1) + B(n)*cos(n*C(f));
                q(n) = q(n-1) + B(n)*sin(n*C(f));
        end
        'calculates the m(n)s for the range of c';
        for n = 1:ncut
            m = 0;
            for j = 1:(N-n)
                m = m + (p(n+j)-p(j))^2 + (q(n+j)-q(j))^2;
            end
            m = m/(N-n);
            Vosc = (E^2)*((1-cos(n*C(f)))/(1-cos(C(f))));
            D(n) = m - Vosc;
        end
        'creates a vector containing the values of k for each value of c';
        K(f) = corr(X,D);
    end
    'calculates the value of k to be plotted and stores it';
    k = median(K);
    KC(b) = k;
    'outputs how far through the program you''ve gotten so far';
    percents = ((count*aacc)/(an-a1))*100
end
'plots k against mu';
plot(A,KC)