Artemis Fowl
Artemis Fowl

Reputation: 301

Matlab generate multiple random matrices

I have to generate 20 random matrices, of increasing sizes

200:50:1150 //sizes of 20 random matrices

I want to store them in like an array of matrices:

like

array(1) // should give me the 1st matrix of size 200x200
array(2) // should give me the 2nd matrix of size 250x250 and so on

I am not sure how to do this:

n = 200:50:1150
for i=1:20
  M(:,:,i) = rand(n(i));   //This does not work
end

How do I do this, is there a faster way without loops?

Upvotes: 1

Views: 127

Answers (1)

Daniel
Daniel

Reputation: 36710

You can not stack your matrices of different sizes into a 3d matrix, a matrix has fixed dimensions. Use a cell array instead:

n = 200:50:1150;
M=cell(1,numel(n));
for ix=1:numel(n);
  M{ix} = rand(n(ix)); 
end

Not using a for loop won't increase the performance. Simply generating the same amount of random numbers in a single call takes the same time: rand(sum(n.^2),1);

Upvotes: 1

Related Questions