Create matrix using the array as index

조회 수: 13 (최근 30일)
HASAN AL-KAF
HASAN AL-KAF 2021년 10월 8일
답변: Rik 2021년 10월 8일
Hi,
I have an array of 1*2000 double. I want to create matrix of 6*2000 double. so only the index of the value is 1 and the others is zero in each columns.
for example if my array is a=[2 2 1 0 3]
the ouput of of matrix will be same as the image below?
Thank you.

채택된 답변

Rik
Rik 2021년 10월 8일
You don't even need a loop:
a=[2 2 1 0 3];
ind=a+1;
A=zeros(max(ind),numel(ind));
ind=sub2ind(size(A),ind,1:numel(ind));
A(ind)=1
A = 4×5
0 0 0 1 0 0 0 1 0 0 1 1 0 0 0 0 0 0 0 1

추가 답변 (1개)

per isakson
per isakson 2021년 10월 8일
Try this
M = zeros(5,5);
a = [2,2,1,0,3];
for jj = 1:5
M(a(jj)+1,jj)=1;
end
disp(M)
0 0 0 1 0 0 0 1 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by