Two-sample t-test - MATLAB ttest2 - MathWorks

文章推薦指數: 80 %
投票人數:10人

This MATLAB function returns a test decision for the null hypothesis that the data in vectors x and y comes from independent random samples from normal ... Skiptocontent HelpCenterHelpCenter SearchHelpCenter HelpCenter MathWorks SearchMathWorks.com MathWorks Support CloseMobileSearch OpenMobileSearch Off-CanvasNavigationMenuToggle DocumentationHomeAI,DataScience,andStatistics StatisticsandMachineLearningToolbox ProbabilityDistributionsContinuousDistributionsStudent'stDistributionStatisticsandMachineLearningToolbox HypothesisTests ttest2 Onthispage SyntaxDescriptionExamplesTwo-Samplet-TestforEqualMeanst-TestforEqualMeansWithoutAssumingEqualVariancesOne-Sided,Two-Samplet-TestInputArgumentsxyName-ValueArgumentsAlphaDimTailVartypeOutputArgumentshpcistatsMoreAboutTwo-Samplet-testMultidimensionalArrayFirstNonsingletonDimensionTipsExtendedCapabilitiesVersionHistorySeeAlso DocumentationExamplesFunctionsBlocksAppsVideosAnswers TrialSoftware TrialSoftware ProductUpdates ProductUpdates Resources DocumentationExamplesFunctionsBlocksAppsVideosAnswers MainContent ttest2Two-samplet-testcollapseallinpage Syntaxh=ttest2(x,y)h=ttest2(x,y,Name,Value)[h,p]= ttest2(___)[h,p,ci,stats] =ttest2(___)Descriptionexampleh=ttest2(x,y)returns atestdecisionforthenullhypothesisthatthedatainvectorsxandycomes fromindependentrandomsamplesfromnormaldistributionswithequal meansandequalbutunknownvariances,usingthetwo-samplet-test. Thealternativehypothesisisthatthedatainxandycomes frompopulationswithunequalmeans.Theresulthis1if thetestrejectsthenullhypothesisatthe5%significancelevel, and0otherwise.exampleh=ttest2(x,y,Name,Value)returns atestdecisionforthetwo-samplet-testwith additionaloptionsspecifiedbyoneormorename-valuepairarguments. Forexample,youcanchangethesignificancelevelorconductthe testwithoutassumingequalvariances.example[h,p]= ttest2(___)alsoreturnsthep-value,p, ofthetest,usinganyoftheinputargumentsintheprevioussyntaxes.example[h,p,ci,stats] =ttest2(___)alsoreturnstheconfidenceinterval onthedifferenceofthepopulationmeans,ci, andthestructurestatscontaininginformation abouttheteststatistic.ExamplescollapseallTwo-Samplet-TestforEqualMeansOpenLiveScriptLoadthedataset.Createvectorscontainingthefirstandsecondcolumnsofthedatamatrixtorepresentstudents’gradesontwoexams.loadexamgrades x=grades(:,1); y=grades(:,2);Testthenullhypothesisthatthetwodatasamplesarefrompopulationswithequalmeans.[h,p,ci,stats]=ttest2(x,y)h=0 p=0.9867 ci=2×1 -1.9438 1.9771 stats=structwithfields: tstat:0.0167 df:238 sd:7.7084 Thereturnedvalueofh=0indicatesthatttest2doesnotrejectthenullhypothesisatthedefault5%significancelevel.t-TestforEqualMeansWithoutAssumingEqualVariancesOpenLiveScriptLoadthedataset.Createvectorscontainingthefirstandsecondcolumnsofthedatamatrixtorepresentstudents’gradesontwoexams.loadexamgrades x=grades(:,1); y=grades(:,2);Testthenullhypothesisthatthetwodatavectorsarefrompopulationswithequalmeans,withoutassumingthatthepopulationsalsohaveequalvariances.[h,p]=ttest2(x,y,'Vartype','unequal')h=0 p=0.9867 Thereturnedvalueofh=0indicatesthatttest2doesnotrejectthenullhypothesisatthedefault5%significancelevelevenifequalvariancesarenotassumed.One-Sided,Two-Samplet-TestOpenLiveScriptLoadthesampledata.Createacategoricalvectortolabelthevehiclemileagedataaccordingtothevehicleyear.loadcarbig.mat; decade=categorical(Model_Year<80,[true,false],["70s","80s"]);Plotboxchartsofthemileagedataforeachdecade.boxchart(decade,MPG) xlabel("Decade") ylabel("Mileage")Createvectorsfromthemileagedataforeachdecade.Usealeft-tailed,two-samplet-testtotestthenullhypothesisthatthedatacomesfrompopulationswithequalmeans.Usethealternativehypothesisthatthepopulationmeanforthemileageofcarsmadeinthe1970sislessthanthepopulationmeanforthemileageofcarsmadeinthe1980s.MPG70s=MPG(decade=="70s"); MPG80s=MPG(decade=="80s"); [h,~,~,stats]=ttest2(MPG70s,MPG80s,"Tail","left")h=1 stats=structwithfields: tstat:-14.0630 df:396 sd:6.3910 Thereturnedvalueofh=1indicatesthatttest2rejectsthenullhypothesisatthedefaultsignificancelevelof5%,infavorofthealternativehypothesisthatthepopulationmeanforthemileageofcarsmadeinthe1970sislessthanthepopulationmeanforthemileageofcarsmadeinthe1980s.PlotthecorrespondingStudent'st-distribution,thereturnedt-statistic,andthecriticalt-value.Calculatethecriticalt-valueatthedefaultconfidencelevelof95%byusingtinv.nu=stats.df; k=linspace(-15,15,300); tdistpdf=tpdf(k,nu); tval=stats.tstattval=-14.0630 tvalpdf=tpdf(tval,nu); tcrit=-tinv(0.95,nu)tcrit=-1.6487 plot(k,tdistpdf) holdon scatter(tval,tvalpdf,"filled") xline(tcrit,"--") legend(["Student'stpdf","t-statistic",... "CriticalCutoff"])Theorangedotrepresentsthet-statisticandislocatedtotheleftofthedashedblacklinethatrepresentsthecriticalt-value.InputArgumentscollapseallx—Sampledatavector|matrix|multidimensionalarray Sampledata,specifiedasavector,matrix,ormultidimensional array.ttest2treatsNaNvalues asmissingdataandignoresthem. Ifxandyare specifiedasvectors,theydonotneedtobethesamelength.Ifxandyare specifiedasmatrices,theymusthavethesamenumberofcolumns.ttest2performs aseparatet-testalongeachcolumnandreturns avectorofresults.Ifxandyare specifiedasmultidimensional arrays,theymusthavethesamesizealongallbutthefirstnonsingleton dimension. DataTypes:single|doubley—Sampledatavector|matrix|multidimensionalarray Sampledata,specifiedasavector,matrix,ormultidimensional array.ttest2treatsNaNvalues asmissingdataandignoresthem. Ifxandyare specifiedasvectors,theydonotneedtobethesamelength.Ifxandyare specifiedasmatrices,theymusthavethesamenumberofcolumns.ttest2performs aseparatet-testalongeachcolumnandreturns avectorofresults.Ifxandyare specifiedasmultidimensional arrays,theymusthavethesamesizealongallbutthefirstnonsingleton dimension.ttest2worksalongthefirst nonsingletondimension. DataTypes:single|doubleName-ValueArgumentsSpecifyoptionalpairsofargumentsas Name1=Value1,...,NameN=ValueN,whereNameis theargumentnameandValueisthecorrespondingvalue. Name-valueargumentsmustappearafterotherarguments,buttheorderofthe pairsdoesnotmatter. BeforeR2021a,usecommastoseparateeachnameandvalue,andenclose Nameinquotes. Example:'Tail','right','Alpha',0.01,'Vartype','unequal'specifies aright-tailedtestatthe1%significancelevel,anddoesnotassume thatxandyhaveequalpopulation variances.Alpha—Significancelevel0.05(default)|scalarvalueintherange(0,1) Significancelevelofthehypothesistest,specifiedasthe comma-separatedpairconsistingof'Alpha'and ascalarvalueintherange(0,1). Example:'Alpha',0.01 DataTypes:single|doubleDim—Dimensionfirstnonsingletondimension(default)|positiveintegervalue Dimensionoftheinputmatrixalongwhichtotestthemeans, specifiedasthecomma-separatedpairconsistingof'Dim'and apositiveintegervalue.Forexample,specifying'Dim',1tests thecolumnmeans,while'Dim',2teststherowmeans. Example:'Dim',2DataTypes:single|doubleTail—Typeofalternativehypothesis'both'(default)|'right'|'left' Typeofalternativehypothesistoevaluate,specifiedasthecomma-separatedpairconsisting of'Tail'andoneof: 'both'—Testagainstthe alternativehypothesisthatthepopulationmeansarenot equal.'right'—Testagainstthe alternativehypothesisthatthepopulationmeanof xisgreaterthanthepopulationmean ofy.'left'—Testagainstthe alternativehypothesisthatthepopulationmeanof xislessthanthepopulationmeanof y. ttest2teststhenullhypothesisthatthe populationmeansareequalagainstthespecifiedalternative hypothesis. Example:'Tail','right' Vartype—Variancetype'equal'(default)|'unequal' Variancetype,specifiedasthecomma-separatedpairconsisting of'Vartype'andoneofthefollowing. 'equal'Conducttestusingtheassumptionthatxandyare fromnormaldistributionswithunknownbutequalvariances.'unequal'Conducttestusingtheassumptionthatxandyare fromnormaldistributionswithunknownandunequalvariances.This iscalledtheBehrens-Fisherproblem.ttest2uses Satterthwaite’sapproximationfortheeffectivedegreesof freedom. Vartypemustbeasinglevariancetype,even whenxisamatrixoramultidimensionalarray. Example:'Vartype','unequal' OutputArgumentscollapseallh—Hypothesistestresult1|0 Hypothesistestresult,returnedas1or0. Ifh=1, thisindicatestherejectionofthenullhypothesisattheAlphasignificance level.Ifh=0, thisindicatesafailuretorejectthenullhypothesisattheAlphasignificance level. p—p-valuescalarvalueintherange[0,1] p-valueofthetest,returnedasascalar valueintherange[0,1].pistheprobability ofobservingateststatisticasextremeas,ormoreextremethan, theobservedvalueunderthenullhypothesis.Smallvaluesofpcast doubtonthevalidityofthenullhypothesis. ci—Confidenceintervalvector Confidenceintervalforthedifferenceinpopulationmeansofxandy, returnedasatwo-elementvectorcontainingthelowerandupperboundaries ofthe100×(1–Alpha)%confidence interval. stats—Teststatisticsstructure Teststatisticsforthetwo-samplet-test, returnedasastructurecontainingthefollowing: tstat—Valueofthetest statistic.df—Degreesoffreedom ofthetest.sd—Pooledestimateof thepopulationstandarddeviation(fortheequalvariancecase)or avectorcontainingtheunpooledestimatesofthepopulationstandard deviations(fortheunequalvariancecase). MoreAboutcollapseallTwo-Samplet-testThetwo-samplet-testis aparametrictestthatcomparesthelocationparameteroftwoindependent datasamples.Theteststatisticis t=x¯−y¯sx2n+sy2m,wherex¯andy¯arethesamplemeans,sxandsyare thesamplestandarddeviations,andnandmare thesamplesizes.Inthecasewhereitisassumedthatthetwodatasamplesare frompopulationswithequalvariances,theteststatisticunderthe nullhypothesishasStudent'stdistribution withn+m– 2degreesoffreedom,andthesamplestandard deviationsarereplacedbythepooledstandarddeviation s=(n−1)sx2+(m−1)sy2n+m−2.Inthecasewhereitisnotassumedthatthetwodatasamples arefrompopulationswithequalvariances,theteststatisticunder thenullhypothesishasanapproximateStudent'stdistribution withanumberofdegreesoffreedomgivenbySatterthwaite'sapproximation. ThistestissometimescalledWelch’st-test.MultidimensionalArrayAmultidimensionalarrayhasmorethantwo dimensions.Forexample,ifxisa1-by-3-by-4 array,thenxisathree-dimensionalarray.FirstNonsingletonDimensionThefirstnonsingletondimensionisthefirst dimensionofanarraywhosesizeisnotequalto1.Forexample,ifxis a1-by-2-by-3-by-4array,thentheseconddimensionisthefirstnonsingleton dimensionofx.TipsUsesampsizepwrto calculate:Thesamplesizethatcorrespondstospecifiedpower andparametervalues;Thepowerachievedforaparticularsamplesize,given thetrueparametervalue;Theparametervaluedetectablewiththespecified samplesizeandpower.ExtendedCapabilitiesGPUArraysAcceleratecodebyrunningonagraphicsprocessingunit(GPU)usingParallelComputingToolbox™.ThisfunctionfullysupportsGPUarrays.Formoreinformation,seeRunMATLABFunctionsonaGPU(ParallelComputingToolbox).VersionHistoryIntroducedbeforeR2006aSeeAlsottest|ztest|sampsizepwr × OpenExample Youhaveamodifiedversionofthisexample.Doyouwanttoopenthisexamplewithyouredits? No,overwritethemodifiedversion Yes × MATLABCommand YouclickedalinkthatcorrespondstothisMATLABcommand: RunthecommandbyenteringitintheMATLABCommandWindow. WebbrowsersdonotsupportMATLABcommands. Close × SelectaWebSite Chooseawebsitetogettranslatedcontentwhereavailableandseelocaleventsandoffers.Basedonyourlocation,werecommendthatyouselect:. Switzerland(English) Switzerland(Deutsch) Switzerland(Français) 中国(简体中文) 中国(English) Youcanalsoselectawebsitefromthefollowinglist: HowtoGetBestSitePerformance SelecttheChinasite(inChineseorEnglish)forbestsiteperformance.OtherMathWorkscountrysitesarenotoptimizedforvisitsfromyourlocation. Americas AméricaLatina(Español) Canada(English) UnitedStates(English) Europe Belgium(English) Denmark(English) Deutschland(Deutsch) España(Español) Finland(English) France(Français) Ireland(English) Italia(Italiano) Luxembourg(English) Netherlands(English) Norway(English) Österreich(Deutsch) Portugal(English) Sweden(English) Switzerland Deutsch English Français UnitedKingdom(English) AsiaPacific Australia(English) India(English) NewZealand(English) 中国 简体中文 English 日本(日本語) 한국(한국어) Contactyourlocaloffice TrialSoftware TrialSoftware ProductUpdates ProductUpdates



請為這篇文章評分?