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