1
votes

I would like to generate a very large matrix of the form:

[[1,2,3]
,[2,3,4]
,[3,4,5]
...
,[n,n+1,n+2]]

for values of n up to a million or more. How do you do this in matlab/octave?

I'm used to functional programming where I would generate a large list from [1..n] and map a transforming function on to that list. I assume matlab/octave has a similar idiom for generating large matrices, but I can't find anything.

4

4 Answers

3
votes

Let r and c be the number of rows and columns of your desired matrix, then

M = bsxfun(@plus, 0:c-1, (1:r)');
2
votes

This should work:

n=100000;    
A=[[1:n]' [2:n+1]' [3:n+2]'];
2
votes
A=zeros(n, 3);
for column=1:3
     for row=1:n
           A(row, column) = n + column - 1;
     end
end

Try that. You want to create a matrix of all zeros first because it's a lot more efficient than dynamically updating the matrix at each iteration; especially for very large matrices. You want to iterate through the rows on the inner for-loop because Matlab stores vectors in column-major order so Matlab will not have to keep going between the cache and main memory to do these operations as it would if you were iterating through the columns at the inner for loop. (It still will just a lot less often).

1
votes

yet another option:

 bsxfun(@plus,cumsum(ones(n,1)),[0 1 2]);