Effacer les filtres
Effacer les filtres

Create matrix using the array as index

13 vues (au cours des 30 derniers jours)
HASAN AL-KAF
HASAN AL-KAF le 8 Oct 2021
Réponse apportée : Rik le 8 Oct 2021
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.

Réponse acceptée

Rik
Rik le 8 Oct 2021
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

Plus de réponses (1)

per isakson
per isakson le 8 Oct 2021
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

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by