Two-sample t-test - MATLAB ttest2 - MathWorks
文章推薦指數: 80 %
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
延伸文章資訊
- 1test-t - File Exchange - MATLAB Central - MathWorks
Student's t test for unpaired or paired samples. This file is applicable for equal or unequal sam...
- 2How to do paired t test with mean and sd? - MATLAB Answers
I would like to do paired t-test with mean and standard deviation and the number of sampling. Theme.
- 3Lab 03 : Statistical significance tests with MATLAB
Include the MATLAB code snippets in the report or upload them separately. ... Hints Use of paired...
- 4用MATLAB做T检验(ttest) - CSDN博客
t-检验:t-检验,又称student's t-test,可以用于比较两组数据是否来自同一分布(可以用于比较两组数据的区分度),假设了数据的正态性, ...
- 5用MATLAB做T檢驗(ttest) - 台部落
但是這裏至於paired和unpaired之間的區別我卻還沒搞清楚,只是在Student's t-test中看到了如下這樣一段解釋:. “Two-sample t-tests for a dif...