How can I contruct a matrix with elements set to 1 given by the index position in another matrix?
1 次查看(过去 30 天)
显示 更早的评论
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
2 个评论
KALYAN ACHARJYA
2019-11-5
编辑:KALYAN ACHARJYA
2019-11-5
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
采纳的回答
Guillaume
2019-11-5
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!