How can I convert an Array with row values to a binary Matrix?

2 vues (au cours des 30 derniers jours)
Kjell
Kjell le 30 Juin 2023
Commenté : Kjell le 30 Juin 2023
Hi,
I have an array A containing natural numbers. The indices of the array represent the current column and the numbers itself represent the rows of a matrix M. Now I want to set the matrix at one for the corresponding values in the array.
Like the following code
A = [2 3 3 4 5 4 3];
M = zeros(length(A));
for i= 1:length(A)
M(A(i),i) = 1;
end
M
M = 7×7
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
I know that using loops in Matlab can be very slow and I want a faster way of computing this, since the array in my project has a length of 60000. Is there a way to run compute this faster?

Réponse acceptée

Cris LaPierre
Cris LaPierre le 30 Juin 2023
Porabbly with sub2ind.
A = [2 3 3 4 5 4 3];
M = zeros(length(A));
Col = 1:length(A);
ind = sub2ind(size(M),A,Col);
M(ind) = 1
M = 7×7
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by