I'd like to have a MATLAB array fill a column with numbers in increments of 0.001. I am working with arrays of around 200,000,000 rows and so would like to use the most efficient method possible. I had considered using the following code:
for i = 1 : size(array,1)
array(i,1) = i * 0.001;
end
There must be a more efficient way of doing this..?
Well the accepted answer is pretty close to being fast but no fast enough. You should use:
s=size(array,1);
step=0.0001;
array(:,1)=[step:step:s*step];
There are two issues with the accepted answer
and here is a comparison (sorry I am running 32-bit matlab)
array=rand(10000);
s=size(array,1);
step=0.0001;
tic
for i=1:100000
array(:,1)=[step:step:s*step];
end
toc
and
tic
for i=1:100000
array(:, 1)=[1:s]'*step;
end
toc
the results are:
Elapsed time is 3.469108 seconds.
Elapsed time is 5.304436 seconds.
and without transposing in the second example
Elapsed time is 3.524345 seconds.
I suppose in your case things would be worst.
array(:,1) = [1:size(array,1)]' * 0.001;
Matlab is more efficient when vectorizing loops, see also the performance tips from mathworks.
If such vectorization is infeasible due to space limitations, you might want to reconsider rewriting your for-loop in C, using a MEX function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With