how to separate a matrix into 2 vectors

11 Ansichten (letzte 30 Tage)
giancarlo maldonado cardenas
giancarlo maldonado cardenas am 17 Mär. 2022
Bearbeitet: Dave B am 17 Mär. 2022
hello guys, I have a problem with separating a matrix into two vectors, if the last column is 0 or 1.
I explain myself better, I have this matrix but as we can see in the last column I have 1 or 0 right? what I want to do is separate it into two groups for example.
matrix file attached.
matrix
60 13.9713945172825 20 1
59 14.3718712753277 43 1
52 21.1752085816448 20 1
48 12.7771156138259 35 0
48 20.7771156138259 35 0
47 15.1775923718712 28 1
44 18.3790226460073 57 1
41 21.5804529201432 8 1
15 21.9928486293206 29 1
12 21.1942789034565 31 1
Result
vectorof1= [60 13.9713945172825 20 1
59 14.3718712753277 43 1
52 21.1752085816448 20 1
47 15.1775923718712 28 1
44 18.3790226460073 57 1
41 21.5804529201432 8 1
15 21.9928486293206 29 1
12 21.1942789034565 31 1];
vectorof0 = [48 12.7771156138259 35 0
48 20.7771156138259 35 0];
thank you very much in advance.

Akzeptierte Antwort

Dave B
Dave B am 17 Mär. 2022
Bearbeitet: Dave B am 17 Mär. 2022
You can do this pretty easily with some indexing. Here's an example with some random data:
m = [rand(10,2) randi(2,10,1)-1]
m = 10×3
0.6389 0.4429 1.0000 0.0720 0.4878 0 0.8781 0.6126 0 0.8703 0.5697 0 0.4551 0.6683 1.0000 0.8022 0.4067 0 0.2758 0.1283 0 0.5673 0.0117 1.0000 0.1495 0.2832 0 0.0861 0.4779 0
m0 = m(m(:,3)==0,:) % read the right hand side as: from m, take the rows where the third column of m is 0, take all columns
m0 = 7×3
0.0720 0.4878 0 0.8781 0.6126 0 0.8703 0.5697 0 0.8022 0.4067 0 0.2758 0.1283 0 0.1495 0.2832 0 0.0861 0.4779 0
m1 = m(m(:,3)==1,:) % read the right hand side as: from m, take the rows where the third column of m is 1, take all columns
m1 = 3×3
0.6389 0.4429 1.0000 0.4551 0.6683 1.0000 0.5673 0.0117 1.0000
To understand how this works, you can look at what you're feeding in:
ind = m(:,3)==1
ind = 10×1 logical array
1 0 0 0 1 0 0 1 0 0
(importantly it's displayed as 1 and 0, but note it's a "logical array" it's really true, false, false, false, true, ...)

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by