rajan sthapit
rajan sthapit

Reputation: 4354

Initializing a matrix with a certain value in matlab

I have this matrix A of size 100x100. Now I have another vector Z=(1,24,5,80...) which has 100 elements. it is a column vector with 100 elements. Now for each row of the matrix A, I want its A(i,j) element to be 1 where i is the row from 1:100 and j is the column which is given by Z

So the elements that should be 1 should be 1,1 2,24 3,5 4,80 and so on

I know I can do it using a loop. But is there a direct simple way I mean one liner?

Upvotes: 0

Views: 1332

Answers (2)

user85109
user85109

Reputation:

A matrix that has 100 non-zero elements out of 10000 (so only 1% non-zero) in total is best stored as sparse. Use the capability of matlab.

A = sparse(1:100,Z,1,100,100);

This is a nice, clean one-linear, that results in a matrix that will be stored more efficiently that a full matrix. It can still be used for matrix multiplies, and will be more efficient at that too. For example...

Z = randperm(100);
A = sparse(1:100,Z,1,100,100);

whos A

  Name        Size             Bytes  Class     Attributes
  A         100x100             2408  double    sparse    

This is a reduction in memory of almost 40 to 1. And, while the matrix is actually rather small as these things go, it is still faster to use it as sparse.

B = rand(100);
timeit(@() B*A)
ans =
   4.5717e-05

Af = full(A);
timeit(@() B*Af)
ans =
   7.4452e-05

Had A been 1000x1000, the savings would have been even more significant.

If your goal is a full matrix, then you can use full to convert it to a full matrix, or accumarray is an option. And if you want to insert values into an existing array, then use sub2ind.

Upvotes: 3

Eitan T
Eitan T

Reputation: 32930

One way to do it is to convert the values in Z to absolute indices in A using sub2ind, and then use vector indexing:

idx = sub2ind(size(A), 1:numel(Z), Z);
A(idx) = 1;

or simply in a one-liner:

A(sub2ind(size(A), 1:numel(Z), Z)) = 1;

Upvotes: 0

Related Questions