Can these two for loops be avoided?

I'm currently stuck with this double for loop. Any way I can avoid this?
points = zeros(1000000,2);
counter = 1;
for i=1:1000
for j=501:1500
points(counter,:) = [i j];
counter = counter + 1;
end
end

 Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 5 Nov 2012
Edited: Azzi Abdelmalek on 5 Nov 2012
n=1000;
m=10;
out=[ reshape(repmat(1:n,m,1),[],1), repmat((1:m)',n,1)]
%or
out=cell2mat(arrayfun(@(x) [ones(m,1)*x (1:m)'],(1:n)','un',0))

More Answers (1)

points(1:1000, 1) = 1:1000;
points(1:1000, 2) = 501:5000;

2 Comments

Oh crap, that's a bad example. I mean, what if the two vectors have different size, like:
points = zeros(10000,2);
counter = 1;
for i=1:1000
for j=1:10
points(counter,:) = [i j];
counter = counter + 1;
end
end
You can do it with repmat() and imresize() (if you have the Image Processing Toolbox).
numberOfRows = 10000;
column1 = imresize((1:1000)', [numberOfRows 1], 'nearest')
column2 = repmat((1:10)', [numberOfRows/10 1])
points = [column1, column2]

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!