## How can I contruct a matrix with elements set to 1 given by the index position in another matrix?

### Rishi Jagdev (view profile)

on 5 Nov 2019
Latest activity Commented on by Rishi Jagdev

on 5 Nov 2019

### Guillaume (view profile)

Hello. I have a a matrix that tells me which of the positions in the other matrix should be set to one. For example-
[2,3,4;3,4,5;1,2,3]
Tells me that I need a matrix like this :
[0 0 1 1 1 0 ; 0 0 0 1 1 1; 0 1 1 1 0 0 ]
How can I obtain this? Thanks in advance

KALYAN ACHARJYA

### KALYAN ACHARJYA (view profile)

5 Nov 2019
With Loops:
data=[2,3,4;3,4,5;1,2,3]
max_data=max(data(:));
[r c]=size(data);
result=zeros(r,max_data+1)
for i=1:r
for j=1:c
data1=data(i,j);
result(i,data1+1)=1;
end
end
result
Rishi Jagdev

5 Nov 2019
Thank you :)

Guillaume

### Guillaume (view profile)

님의 답변 5 Nov 2019
채택된 답변

coloffsets = [2,3,4;3,4,5;1,2,3]
result = zeros(size(coloffsets, 1), 1+max(coloffsets(:)));
result(sub2ind(size(result), repmat((1:size(coloffsets, 1))', 1, size(coloffsets, 2)), 1+coloffsets)) = 1

Rishi Jagdev

### Rishi Jagdev (view profile)

on 5 Nov 2019
Thank you very much :)