Mike Izbicki
Mike Izbicki

Reputation: 6366

How to generate large matrices in matlab/octave?

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.

Upvotes: 1

Views: 2106

Answers (4)

bla
bla

Reputation: 26069

yet another option:

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

Upvotes: 1

user1214845
user1214845

Reputation:

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

Upvotes: 2

Autonomous
Autonomous

Reputation: 9075

This should work:

n=100000;    
A=[[1:n]' [2:n+1]' [3:n+2]'];

Upvotes: 2

H.Muster
H.Muster

Reputation: 9317

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

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

Upvotes: 3

Related Questions