我需要创建一个1e7 x 9值的数组。所有行都是不同的,但所有列都是第一行的副本:
n=1e7; %simulations
t=1:8; %contacts
lambdaU=repmat(rand(n,1),1,length(t)+1) %<<<<<<<Here
CalcTimU=zeros(n,length(t)+1);
%I then do:
for j=1:n %for each simulation (row)
for i=2:length(t)+1 % for each column
CalcTimU(j,i)=CalcTimU(j,i-1)+lambdaU(j,i).*(10-CalcTimU(j,i-1));
end
end
这似乎非常浪费。有什么方法可以减少存储量?
答案 0 :(得分:1)
好的。您甚至可以向量化 j 循环:
n=1500; %simulations
t=1:8; %contacts
lvec = rand(n,1);
lambdaU=repmat(lvec,1,length(t)+1); %<<<<<<<Here
CalcTimU=zeros(n,length(t)+1);
tic
%I then do:
for j=1:n %for each simulation (row)
for i=2:length(t)+1 % for each column
CalcTimU(j,i)=CalcTimU(j,i-1)+lambdaU(j,i).*(10-CalcTimU(j,i-1));
end
end
toc
% Vectorized:
tic
CalcTimU2=zeros(n,length(t)+1);
for i=2:length(t)+1
CalcTimU2(:,i) = CalcTimU2(:,i-1)+lvec.*(10-CalcTimU2(:,i-1));
end
toc
isequal(CalcTimU,CalcTimU2)
结果:
Elapsed time is 0.220032 seconds.
Elapsed time is 0.00030899 seconds.
ans = 1