필터 지우기
필터 지우기

How would I split a vector in two based on the data values of 1 or 0?

조회 수: 11 (최근 30일)
Create two vectors from a long vector consiting of 1s and 0s. I have some data to sort and I have the values in binary form in a vector of a 43000x1 consisting of just 1s and 0s. I need to split this vector into two vectors, one consisting of 1s, and the other consisting of the 0s. This will result in two different sized vectors.

채택된 답변

Image Analyst
Image Analyst 2023년 1월 23일
편집: Image Analyst 2023년 1월 23일
vec = randi([0, 1], 43000, 1)
vec = 43000×1
0 0 0 0 0 0 1 1 0 1
mask = vec == 1;
vec0 = vec(~mask);
vec1 = vec(mask);
whos vec0;
Name Size Bytes Class Attributes vec0 21552x1 172416 double
whos vec1
Name Size Bytes Class Attributes vec1 21448x1 171584 double
% Or another way
vec0 = zeros((length(vec) - nnz(vec)), 1);
vec1 = ones(nnz(vec), 1);
whos vec0
Name Size Bytes Class Attributes vec0 21552x1 172416 double
whos vec1
Name Size Bytes Class Attributes vec1 21448x1 171584 double
  댓글 수: 2
Kendell
Kendell 2023년 1월 23일
Thank you, that worked! I have another question to kind of add on to this one if you don't mind. Say that I have a 43000 x 50 matrix, could I organize it based on whether the first column recieved a 1 or a 0? Therefore I could get 2 Matricies. For your example, it would result in a 21448 x 50 Matrix based on 1s and a 21552 x 50 Matrix based on 0s.
Image Analyst
Image Analyst 2023년 1월 23일
Not sure what you mean. A column is more than a single number.
Anyway, you can do masking on the first column and apply that to all columns:
m = randi([0, 1], 43000, 50);
% Make mask based on first column ONLY.
rowsWith1 = m(:, 1) == 1;
m0 = m(~rowsWith1, :);
m1 = m(rowsWith1, :);
whos m0;
Name Size Bytes Class Attributes m0 21326x50 8530400 double
whos m1
Name Size Bytes Class Attributes m1 21674x50 8669600 double
Note however that m0 and m1 will have a mixture of 0s and 1s in columns 2-50. Only the first column will be all 0 or all 1.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by