How to create a matrix of ones and zeros with location of ones based on array that also contains zeros?

1 vue (au cours des 30 derniers jours)
Hi,
I have a vector V= [3 1 1 5 0 4], which contains both zeros and nonzero values, I want to obtain a matrix of ones and zeros with location of ones based on vector V. I tried the following code:
V= [3 1 1 5 0 4]
out=zeros(n,m);
m=numel(V);
n=max(V);
out = zeros(n, m);
idx=sub2ind([n m],V,1:m);
out(idx)=1
but I obtained the error: "Error using sub2ind. Out of range subscript".
If I remove the zero from V, the code above works.
My desired result is:
out =
0 1 1 0 0 0
0 0 0 0 0 0
1 0 0 0 0 0
0 0 0 0 0 1
0 0 0 1 0 0
Is it possible to obtain it without a for loop?
Thanks!

Réponse acceptée

Dyuman Joshi
Dyuman Joshi le 24 Jan 2023
Modifié(e) : Dyuman Joshi le 24 Jan 2023
You get the error because the code includes 0 as an index.
V = [3 1 1 5 0 4];
idx = V~=0;
m = max(V);
n = numel(V);
R = V;
C = 1:n;
Z = zeros(m,n);
out = sub2ind([m n], R(idx), C(idx));
Z(out) = 1
Z = 5×6
0 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by