From: landon donovan on
I have the next code:
clear all
close all
clc
format long
mu=linspace(-3,0,600);
n=3000;
X=[];
B=[];
XX=[];
BB=[];
plot([-exp(1),-exp(1)],[0, -1],'--r');
hold on;
plot([-exp(1), 0],[-1, -1],'--r');
hold on;


for i=1:length(mu)
x0=-exp(1)-0.5;
X=[];
for j=1:n
x0=mu(i)*exp(x0);
X=[X,x0];
Y=mu(i)*ones(1,n);

end

B=[B,Y];
X(1:length(X)-100)=[];
XX=[XX,X];
B(1:length(B)-100)=[];
BB=[BB,B];
end

plot(BB,XX,'.k','markersize',2)

for the XX and BB arrays, matlab says that I should consider preallocating for speed, but how can I make this when Im using the horzcat function?
From: Matt Fig on
Concatenation array-building in MATLAB is a VERY good way to slow down your code. Follow M-Lint's suggestions! The code below runs in .25 seconds and produces the same graph your code makes in 18 seconds.


%%%%%%%%%%%%%%%%%
m = 600;
mu = linspace(-3,0,m);
n = 3000;
XX = zeros(100,m);
BB = XX;
X = zeros(1,n);
plot([-exp(1),-exp(1)],[0, -1],'--r');
hold on;
plot([-exp(1), 0],[-1, -1],'--r');

for ii=1:length(mu)
x0 = -exp(1)-0.5;

for jj=1:n
x0 = mu(ii)*exp(x0);
X(jj) = x0;
end

XX(:,ii) = X((n-99):n);
BB(:,ii) = mu(ii)*ones(1,100);
end

plot(BB(:).',XX(:)','.k','markersize',2)
%%%%%%%%%%%%%%%%%






Note that this could be improved even more. BB can be made with one call to BSXFUN, for example. I believe the XX variable can be made in a vectorized fashion as well, though I don't have time to attempt it now.
 | 
Pages: 1
Prev: need some more
Next: Stopping & Starting M-files