user4916173
user4916173

Reputation:

How can I vectorize slow code in MATLAB to increase peformance?

How can I vectorize this code? At the moment it runs so slow. I'm really stuck and I've spent the last couple of hours trying to vectorize it, however I can't seem to get it to work correctly.

My naive program below works incredibly slowly. N should really be 10,000 but the program is struggling with N = 100. Any advice would be appreciated.

The code wants to iterate through the functions given N times for each value w21. It then plots the last 200 values for each value of w21. The code below does work as expected in terms of the plot but as mentioned is far to slow since for a good plot the values need to be in the thousands.

hold on
% Number of iterations
N = 100;
x = 1; 
y = 1;
z = 1;

for w21 = linspace(-12,-3,N)
    for i = 1:N-1
        y = y_iterate(x,z,w21);
        z = z_iterate(y);
        x = x_iterate(y);
        if i >= (N - 200)
            p = plot(w21,x,'.k','MarkerSize',3);  
        end
    end
end

Required functions:

function val = x_iterate(y)
    val = -3 + 8.*(1 ./ (1 + exp(-y))); 
end
function val = z_iterate(y)
    val = -7 + 8.*(1 ./ (1 + exp(-y)));
end
function val = y_iterate(x,z,w21)
    val = 4 + w21.*(1 ./ (1 + exp(-x))) + 6.*(1 ./ (1 + exp(-z)));
end

Upvotes: 2

Views: 80

Answers (1)

shade
shade

Reputation: 161

I believe it's because of plot. Try:

[X,Y,Z] = deal( zeros(N,N-1) );
w21 = linspace(-12,-3,N);
for i = 1:N
    for j = 1:N-1
        y = y_iterate(x,z,w21(i));
        z = z_iterate(y);
        x = x_iterate(y);
        X(i,j) = x;
        Y(i,j) = y;
        Z(i,j) = z;
    end
end
nn = max(1,N-200);
plot(w21,X(nn:end,:),'.k')

Upvotes: 3

Related Questions