How to create a matrix of ones and zeros with location of ones based on array that also contains zeros?
3 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Dyuman Joshi
on 24 Jan 2023
Edited: Dyuman Joshi
on 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
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!