ronimb
ronimb

Reputation: 390

Creating a cell array of different randomized matrices

I'm trying to create a cell array of size N, where every cell is a randomized Matrix of size M, I've tried using deal or simple assignments, but the end result is always N identical Matrices of size M for example:

N=20;
M=10;
CellArray=cell(1,N);
CellArray(1:20)={rand(M)};

this yields identical matrices in each cell, iv'e tried writing the assignment like so:

CellArray{1:20}={rand(M)};

but this yields the following error:

The right hand side of this assignment has too few values to satisfy the left hand side.

the ends results should be a set of transition probability matrices to be used for a model i'm constructing, there's a currently working version of the model, but it uses loops to create the matrices, and works rather slowly, i'd be thankful for any help

Upvotes: 0

Views: 49

Answers (2)

Daniel
Daniel

Reputation: 36710

If you don't want to use loops because you are interested in a low execution time, get rid of the cells.

RandomArray=rand(M,M,N)

You can access each slice, which is your intended MxM matrix, using RandomArray(:,:,index)

Upvotes: 2

Robert Seifert
Robert Seifert

Reputation: 25232

Use cellfun:

N = 20;
M = 10;

CellArray = cellfun(@(x) rand(M), cell(1,N), 'uni',0)

For every cell it newly calls rand(M) - unlike before, you were assigning the same rand(M) to every cell, which was just computed once.

Upvotes: 1

Related Questions