2

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..?

3 Answers 3

9

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

  1. you don't need to transpose
  2. you should include the step inside the vector, instead of multiplying

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for correct use of the start:step:end syntax for evenly-spaced lists.
@catchmeifyoutry +1 for you nickname :D
3
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.

1 Comment

As g24l pointed out, the transpose is not needed, and even negatively affects performance. I incorrectly assumed Matlab would optimize this (yes, stupid me).
1

you can also try this

size=20000000;%size is defined

array(1:size,1)=(1:size)*0.001

1 Comment

array(:,1) implies array(1:size,1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.