How to create a matrix of ones and zeros with location of ones based on array that also contains zeros?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
esperanta
el 24 de En. de 2023
Editada: Dyuman Joshi
el 24 de En. de 2023
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!
0 comentarios
Respuesta aceptada
Dyuman Joshi
el 24 de En. de 2023
Editada: Dyuman Joshi
el 24 de En. de 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
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrices and Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!