2

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?

1

4 Answers 4

3

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 
Sign up to request clarification or add additional context in comments.

4 Comments

How can I implement same if b is row vector?
What do you mean? b is a row vector in my example and in your question. Do you mean a column? What should the result be then?
sorry column vector. In actual case 'a' is a matrix of size 5000x10 and 'b' is a vector with size 5000x1
@manoos Please see edit. b can now be a row or a column. I'm assuming that b still contains the column indices into a
2

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

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

1 Comment

How can I implement same if b is row vector?
1

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 

Comments

0

any of these methods works in Octave:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.