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

1 次查看(过去 30 天)
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!

采纳的回答

Dyuman Joshi
Dyuman Joshi 2023-1-24
编辑:Dyuman Joshi 2023-1-24
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by