manoos
manoos

Reputation: 1735

How to change elements of a matrix with reference to a vector of column indices without using for-loop?

I have a matrix

a =

   0   0   0   0   0
   0   0   0   0   0
   0   0   0   0   0
   0   0   0   0   0
   0   0   0   0   0
   0   0   0   0   0

and b vector

b =

   1   2   3   4   5   5

I want to replace value of each row in a matrix with reference value of b matrix value and finally generate a matrix as follows without using for loop.

a_new =

   1   0   0   0   0
   0   1   0   0   0
   0   0   1   0   0
   0   0   0   1   0
   0   0   0   0   1
   0   0   0   0   1

if first element of b, b(1) = 1 so change take first row of a vector and make first element as 1 because b(1) = 1.

How can I implement this without using for loop?

Upvotes: 2

Views: 179

Answers (4)

Robert Seifert
Robert Seifert

Reputation: 25232

Same as Luis Mendo's answer, but using the dedicated function sub2ind:

a( sub2ind(size(a),(1:numel(b)).',b(:)) ) = 1

Upvotes: 2

Luis Mendo
Luis Mendo

Reputation: 112659

Sure. You only need to build a linear index from b and use it to fill the values in a:

a = zeros(6,5); % original matrix
b = [1 2 3 4 5 5]; % row or column vector with column indices into a
ind = (1:size(a,1)) + (b(:).'-1)*size(a,1); % build linear index
a(ind) = 1; % fill value at those positions

Upvotes: 3

percusse
percusse

Reputation: 3106

Also via the subscript to indices conversion way,

a = zeros(6,5);
b = [1 2 3 4 5 5];
idx = sub2ind(size(a), [1:6], b); % 1:6 just to create the row index per b entry
a(idx) = 1

Upvotes: 1

rahnema1
rahnema1

Reputation: 15837

any of these methods works in Octave:

bsxfun(@eq,  [1:5 5]',(1:5))

[1:5 5].' == (1:5)

Upvotes: 0

Related Questions