Writing more efficient Matlab code to test Null hypothesis (T and P values)

Hello Matlab experts,
I have data given in a table shown in the attached picture. What I need to do is to extract math score for female and male students and to test the Null hypothesis that there is no significant difference in the scores.
This is my Matlab code that works and provides expected results. I wonder if this can be writte more efficient or shorter.
% Read the table from the csv file
table = readtable('scores.csv');
% Determine indicies for 'female'
idf = find(ismember(table{:,1}, 'female'))
% Determine indicies for 'male'
idm = find(ismember(table{:,1}, 'male'))
% Extract math scores
math_scores = table{:,6};
% Separate femal scores from male scores
female_scores = math_scores(idf);
male_scores = math_scores(idm);
% Perform testing
[h,p,CI,STATS] = ttest2(male_scores, female_scores)
fprintf('T values = %g\n', STATS.tstat)
fprintf('P values = %g\n', p)

 채택된 답변

Adam Danz
Adam Danz 2022년 7월 21일
편집: Adam Danz 2022년 7월 21일
Assuming your table has variable names shown in your image,
% Read the table from the csv file
table = readtable('scores.csv');
isMale = strcmpi(table.gender, 'male');
[h,p,CI,STATS] = ttest2(table.mathScore(isMale), table.mathScore(~isMale));
if gender is not binary,
isMale = strcmpi(table.gender, 'male');
isFemale = strcmpi(table.gender, 'female');
[h,p,CI,STATS] = ttest2(table.mathScore(isMale), table.mathScore(isFemale));
Lesson learned:
  1. use strcmp, strcmpi to compare strings, not ismember.
  2. use dot-indexing with tables instead of { }
  3. You can use indexing directly in input arguments rather than storing indexed results as variables (although that's fine too unless your tables are very big).

추가 답변 (1개)

Askic V
Askic V 2022년 7월 21일
Thank you both Adam Danz and Start Strider, very helpful.

카테고리

도움말 센터File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

질문:

2022년 7월 21일

답변:

2022년 7월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by