Selecting Specific Elements in a Matrix Using Group

9 次查看(过去 30 天)
Hello, I am trying to select elements only from a single group from my data.
Let's say my current code is:
Height = [62; 65; 63; 70; 58; 70; 73]
Gender = [1; 1; 1; 2; 1; 2; 2] % where 1 is female and 2 is male
data_table = [Height(:), Gender(:)]
From the table, I would like to separate the male and female heights and put them into their own separate vectors so I can perform a two-sample t-test. Can anyone help me with this?
Thank you

采纳的回答

the cyclist
the cyclist 2022-8-26
编辑:the cyclist 2022-8-26
Height = [62; 65; 63; 70; 58; 70; 73];
Gender = [1; 1; 1; 2; 1; 2; 2]; % where 1 is female and 2 is male
data_table = [Height(:), Gender(:)];
Height_F = Height(Gender==1)
Height_F = 4×1
62 65 63 58
Height_M = Height(Gender==2)
Height_M = 3×1
70 70 73
or
Height_F = data_table(data_table(:,2)==1,1)
Height_F = 4×1
62 65 63 58

更多回答(1 个)

rumin diao
rumin diao 2022-8-26
you can use the function 'find' to locate different gender:
%current code
Height = [62; 65; 63; 70; 58; 70; 73];
Gender = [1; 1; 1; 2; 1; 2; 2]; % where 1 is female and 2 is male
data_table = [Height(:), Gender(:)];
%seperate female
female = find(Gender == 1);
heightOfFemale = Height(female);
male = find(Gender == 2);
heightOfMale = Height(male);
  1 个评论
the cyclist
the cyclist 2022-8-31
find is a waste of code here, because logical indexing will handle it (which is exactly what my solution did):
%current code
Height = [62; 65; 63; 70; 58; 70; 73];
Gender = [1; 1; 1; 2; 1; 2; 2]; % where 1 is female and 2 is male
%seperate female
female = (Gender == 1);
heightOfFemale = Height(female)
heightOfFemale = 4×1
62 65 63 58
male = (Gender == 2);
heightOfMale = Height(male)
heightOfMale = 3×1
70 70 73

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Preprocessing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by