




下載本文檔
版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
第第2數(shù)據(jù)及其運(yùn)算1、數(shù)值表示、變量及表達(dá)式2、矩陣(數(shù)組)的表示及各種運(yùn)算3、字符串及空數(shù)組(emptyarray)4、元胞數(shù)組(cellarray)5、結(jié)構(gòu)數(shù)組(structure數(shù)據(jù)類型及運(yùn)算數(shù)據(jù)類型及運(yùn)算數(shù)據(jù)類型非常豐富,除數(shù)值型、字符型等基本數(shù)據(jù)類型外,還有結(jié)構(gòu)體、單元等更為復(fù)雜的數(shù)據(jù)類型。各種數(shù)據(jù)類型都以矩陣形式存在,矩陣是最基本的數(shù)據(jù)對(duì)象,并且矩陣的運(yùn)算是定義在復(fù)數(shù)域上的。Data Numeric Multidimensional StructuresandCell2.1數(shù)值表示、變量及表達(dá)式 數(shù)值的記述的數(shù)只采用 的?進(jìn)制表示,可以帶小數(shù)點(diǎn)和負(fù)號(hào);其缺省的數(shù)據(jù)類型為雙精度浮點(diǎn)型(double)。例如 - 1.256e- 變量命令規(guī)則 變量名、函數(shù)名對(duì)字母的?小寫(xiě)是敏感的。如myVar與myvar表示兩個(gè)不同的變量。 變量名第?個(gè)字母必須是英?字母 變量名可以包含英?字母、下劃線和數(shù)字 變量名不能包含空格、標(biāo)點(diǎn) 變量名最多可包含63個(gè)字符(6.5及以后的版本)
Application 2.1數(shù)值表示、變量及表達(dá)式(續(xù)變量意最近的計(jì)變量意最近的計(jì)算結(jié)果的變定義的正的極小值=2.2204e-圓周率∞值,無(wú)限i或虛數(shù)單元,sqrt(-非數(shù),0/0、∞/ 中,被0除不會(huì)引起程序中斷,給出的同時(shí)用inf或NaN給出結(jié) 用戶只能臨時(shí)覆蓋這些預(yù)定義變量的值,Clear或重啟可恢復(fù)其值
Application inta;doubleb;floatc; Na;doubleb;floatc; Allvariablesarecreatedwithdoubleprecisionunlessspecifiedandtheyarematrices. Afterthesestatements,thevariablesare1x1matriceswithdoubleprecision Aregionofmemorycontaininganarray,whichisknownbyauser-specifiedname. Contentscanbeusedormodifiedatany Variablenamesmustbeginwithaletter,followedbyanycombinationofletters,numbersandtheunderscore(_)character.Onlythefirst31charactersaresignificant. languageisCaseSensitive.NAME,andNamearealldifferentGivemeaningful(descriptiveandeasy-to-remember)namesforthevariables.Neverdefineavariablewiththesamenameasa functionorcommand.7Commondatatypesof double:64-bitdouble-precisionfloating-pointnumbersTheycanholdreal,imaginaryorcomplexnumbersintherangefrom±10-308to±10308with15or16decimal>>var=1+i char:16-bitvalues,eachrepresentingasingleThechararraysareusedtoholdcharacter>>comment=‘Thisisacharacterstring’TheThetypeofdataassignedtoavariabledeterminestypeofvariablethatis8VariableLocalIngeneral,avariableinhaslocalscope,thatis,it’savailableinitsThevariabledisappearswhentheworkspaceceasestoRecallthatascriptdoesnotdefineanewworkspace–becareful,otherwiseyoucansteponvariablesdefinedatthelevelwherethescriptisinvokedSinceafunctiondefinesitsownworkspace,avariabledefinedinfunctionislocaltothatVariablesdefinedoutsidethefunctionshouldbepassedtofunctionarguments.Furthermore,theargumentsarepassedbyEveryvariabledefinedinthesubroutine,iftobeusedoutsidethebodyofthefunctionshouldbereturnedbacktothecallingVariableGlobalThesearevariablesthatareavailableinmultipleTheyhavetobeexplicitlydeclaredasbeingNotgoingtoexpandonthis,sinceusingglobalvariablesareaNoteonreturningvaluesfromaSinceallvariablesarelocalandinputargumentsarepassedbyvalue,whenreturningfromafunctionavariablethatismodifiedinthefunctionwillnotappearasmodifiedinthecallingworkspaceunlessthevariableiseitherglobal,ordeclaredareturnvariableforthat Everything(almost)istreatedasadouble-precisionfloatingpointarraybydefault Typedvariables(integer,float,char,…)aresupported,butusuallyusedonlyforspecificapplications.Notalloperationsaresupportedforalltypedvariables. [IDLusestypedvariables,butallowsmixingoftypes...atleasttosomeextent]Thenum2str()andint2str()>>d=[num2str(16)'-Feb-'num2str(2004)>>16-Feb->>x=>>disp(['answer='num2str(x)]answer=>>disp(['answer='int2str(x)]answer=InitializingVariablesinAssignmentAnassignmentstatementhasteralvar=>>var=40*>>var2=var/>>array=[123>>x=1;y=>>a=>>b=[1.02.03.0>>c=[1.0;2.0;>>d=[1,2,3;4,5,>>e=[1,2,4,5,
>>a2=[0>>b2=[a2(2)7>>c2(2,3)=>>d2=[1>>d2(4)=‘;’semicolonsuppressestheautomaticechoingofvaluesbutitslowsdowntheexecution.InitializingVariablesinAssignment ArraysareconstructedusingbracketsandAlloftheelementsofanarrayarelistedinrow Thevaluesineachrowarelistedfromlefttorighttheyareseparatedbyblankspacesor Therowsareseparatedbysemicolonsornew ThenumberofelementsineveryrowofanarraybethenTheexpressionsusedtoinitializearrayscanincludealgebraicoperationsandallorportionsofpreviouslydefinedarrays.InitializingwithShortcutfirst:increment:Colonoperator:ashortcutnotationusedtoinitializearrayswiththousandsofelements>>x=1:2:>>angles=(0.01:0.01:1)*Transposeoperator:(′)swapstherowsandcolumnsofanarray>>f=>>g=>>h=[g′g′
h= InitializingwithBuilt-in
>>a=>>b=zeros(2,>>c=[1,2;3,>>d=InitializingwithKeyboardTheinputfunctiondisplaysapromptstringintheCommandWindowandthenwaitsfortheusertomy_val=input(‘Enteraninputvalue:’);in1=input(‘Enterdata:’);in2=input(‘Enterdata:’2.1數(shù)值表示、變量及表達(dá)式(續(xù) 運(yùn)算符和表達(dá)式加+減-乘*除a/b或/或a/b或冪^〖說(shuō) 表達(dá)式的書(shū)寫(xiě)規(guī)則與“手寫(xiě)方式”幾乎完全相同 表達(dá)式按與常規(guī)相同的優(yōu)先級(jí)自左至右執(zhí)行運(yùn)算。優(yōu)先級(jí):指數(shù)運(yùn)算級(jí)別最高,乘除次之,加減最低。 括號(hào)改變運(yùn)算的次
Application 2.1數(shù)值表示、變量及表達(dá)式(續(xù) 復(fù)數(shù)及其運(yùn)算 中復(fù)數(shù)的表達(dá):z=a+bi,其中a、b實(shí)數(shù)。 把復(fù)數(shù)作為?個(gè)整體,象計(jì)算實(shí)數(shù)樣計(jì)算復(fù)數(shù) 【例2.3-1】復(fù)數(shù)z1=3+4i,z2=1+2i,z3=2e6計(jì)算zz1=3+4*i,z2=1+2*i,z3=2*exp(i*pi/6),z=z1*z2/z3z_real=real(z),z_image=imag(z),z_angle=angle(z),z_length=abs(z),
Application 2.2矩陣(數(shù)組)的表 數(shù)組的概念 ?維數(shù)組變量的創(chuàng)建 ?維數(shù)組變量的創(chuàng)建 數(shù)組元素的標(biāo)識(shí)與尋訪 數(shù)組運(yùn)算 數(shù)
Application 2.2.1.數(shù)組(array)的概念 數(shù)組定義:按?(row)和列(column)順序排列的實(shí)數(shù)或復(fù)數(shù)的有序集,被稱為數(shù)組。3254321數(shù)組中的任何?個(gè)數(shù)都被稱為這個(gè)數(shù)組的元素,由其所在的?和列標(biāo)識(shí),這個(gè)標(biāo)識(shí)也稱為數(shù)組元素的下標(biāo)或索3254321對(duì)m?、n列的2維數(shù)組 44a(3,4)=34rowis Application 2.2.1數(shù)組(array)的概念 數(shù)組的分類 ?維數(shù)組,也稱為向量(vector) ?向量(rowvector)、列向量 ?維數(shù)組(矩陣matrix) 數(shù)組 有效矩陣:每?元素的個(gè)數(shù)必須相同,每列元素的個(gè)數(shù)也必須相同。
Application 、數(shù)組(array)的概念(續(xù)行向量列向量
Application 、創(chuàng)建?維數(shù)組變量 第?種?法:使用?括號(hào)“[]”操作【例2-1】創(chuàng)建數(shù)組(?向量)a=[13pi>>a=[13pi3+5*i]%ora=[1,3,pi,a= 3.0000+向量元素間用空格或英?的逗點(diǎn)“,”分開(kāi)。 第?種?法:使用冒號(hào)“:”操作【例2-2】創(chuàng)建以1~10順序排列整數(shù)為元素的?向量b。
Alication 2.2.2、創(chuàng)建?維數(shù)組變量(續(xù)【例2-3】鍵?并執(zhí)?c=1:2:10和>>c=1357d=1357:”操作符創(chuàng)建? Start表示新向量x的第?個(gè)元素; 新向量x的最后?個(gè)元素不能?于End Increment可正可負(fù),若負(fù),則必須Start>End;若正則必須Start<End,否則創(chuàng)建的為空向量。 若Increment=1,則可簡(jiǎn)寫(xiě)為:x=Start:End
Application 2.2.2、創(chuàng)建?維數(shù)組變量(續(xù) 第三種?法:利用函數(shù)函數(shù)linspace的基本語(yǔ)法x=linspace(x1,x2, 【例2-4】鍵?并執(zhí)?x=linspace(1,2,5) 可以在實(shí)驗(yàn)時(shí)察看x=linspace(1,2)執(zhí)?
Application 2.2.2、創(chuàng)建?維數(shù)組變量(續(xù) 第四種?法:利用函數(shù) 列向量的創(chuàng)建 使用?括號(hào)“[]”操作符,使用分號(hào)“;”分割?【例2-5】鍵?并執(zhí)?x=[1;2;23 使用冒號(hào)操作符【例2-6】鍵?并執(zhí)?x= %“’”表示矩陣的轉(zhuǎn)
Application Thecolon(冒號(hào))Thecolon:isoneof ’smostimportantoperators.Ithasmanyuses.3:-2:-11isarowvectorcontainingintegersfrom3to-11withaincrementof-2.Subscript(下標(biāo)) expressionsinvolvingcolonsrefertoportionsofamatrix.A(1:3,2)isthefirsttothethirdelementsofthesecondcolumnofA.2.2.2、創(chuàng)建?維數(shù)組變量(續(xù) 創(chuàng)建數(shù)組變量的?般? 創(chuàng)建變量的賦值語(yǔ)句的?般格式?var為變量名?expression為合法表達(dá)??也可以由常數(shù)值、其他變量(部分或全部)【例2-7】鍵?并執(zhí)a=[01+6];b=[a67];c=[6a7];d=[6a7
Application 、創(chuàng)建?維數(shù)組變量(續(xù) ?旦被創(chuàng)建,變量就被 在?作空間,可Window”“whos”命令察看。
Application 、創(chuàng)建?維數(shù)組變量 使用規(guī)則 ?與?之間須用分號(hào)“間隔,也可以在分?處用回車鍵間隔; 【例3-1】鍵?并執(zhí)?a2=[123;456;78 245 8【例3-2】鍵?并執(zhí)?a2=[1:3;4:6;7:9]%結(jié)果同上
Application 、創(chuàng)建?維數(shù)組變量(續(xù)【例3-3】由向量構(gòu)成?維數(shù)組。>>a=[123];b=[23>>c1=[a 第?種?法:函數(shù)?函數(shù)ones(?成全1矩陣)、zeros(?成全0矩陣、 “helpelmat”獲得基本的矩陣?成和操作函數(shù)列表【例3-4】創(chuàng)建全1的3x3數(shù)組?!纠?-5】創(chuàng)建全1的3x4數(shù)組。
Application 、創(chuàng)建?維數(shù)組變量(續(xù)【例3-5】reshape的使用演示>>a=--4-3-2-10123>>b=reshape(a,3,-4-1- 0- 1 數(shù)組元素的排列順序,從上到下按列排列,先排第?列,然后第?列, 要求數(shù)組的元素總數(shù)不變
Application Workingwithprovidesfourfunctionsthatgeneratebasicmatrices.zeros:allzeros.A=zeros(1,3)ones:allones.A=ones(2,4)rand:uniformlydistributedrandomnumbers.A=randn:normallydistributedrandomnumbers.A=randn(2,2)WorkingwithConcatenation:joinsmall(compatible)matricestomakebiggerones.B=[AA-2;A*2A/4]Deletingrowsandcolumns.B(:,2)=[providesalargerangeofstandardelementarymathematicalfunctions,includingabs,sqrt,exp,andForhelponfunctions,helpelfun(elementarymathematicalfunctions)helpspecfun(advancedmathematicalfunctions)helpelmat(advancedmatrixfunctions)helpdatafun ysis、數(shù)組元素的標(biāo)識(shí)與尋訪 數(shù)組元素的標(biāo)識(shí) 如對(duì)于?維數(shù)組,用“?下標(biāo)和列下標(biāo)”標(biāo)識(shí)數(shù)組的元素,a(2,3)表示?維數(shù)組a2?第3素 對(duì)于?維數(shù)組,用?個(gè)下標(biāo)即可,b(2)表示?維數(shù)組b的第2個(gè)素,?論b是?向量還是列向量 ”(linearindex)標(biāo)識(shí) 對(duì)于?維數(shù)組,單下”
Application Subscripts(下標(biāo)TheelementinrowiandcolumnjofAisdenotedbyA(i,j).Example:A=A(1,1)+A(1,2)+2.2.4、數(shù)組元素的標(biāo)識(shí)與尋訪(續(xù)【例4-1】單下標(biāo)的使用>>a=zeros(2,>>a(:)=-a024135%注意數(shù)組的排列順序。
Application 2.2.4、數(shù)組元素的標(biāo)識(shí)與尋訪(續(xù) 元素與?數(shù)組的尋訪與賦值【例4-3】?維數(shù)組元素與?數(shù)組的尋訪與賦值a %尋訪a的第3個(gè)元ans>>a([12 ans
Application 、數(shù)組元素的標(biāo)識(shí)與尋訪(續(xù) >>a(3:-ans%%第3個(gè)及其后所有元素構(gòu)成的子數(shù)ans%函數(shù)end作為參數(shù)使用,返回最后一個(gè)元素的下
>>a(3:end-ans
Application 2.2.4、數(shù)組元素的標(biāo)識(shí)與尋訪(續(xù)>>a([1235532ans 數(shù)組???Indexexceedsmatrix ???Subscriptindicesmusteitherberealpositiveintegers
Application 、數(shù)組元素的標(biāo)識(shí)與尋訪(續(xù) %修改數(shù)組a的第3元素值為0a= >>a([25])=[1a 可以修改指定數(shù)組元素的值 ?次可以修改多個(gè)數(shù)組元素的值 要修改的數(shù)組元素的個(gè)數(shù)應(yīng)與送?數(shù)組的元素個(gè)數(shù)相同
Application 2.2.4、數(shù)組元素的標(biāo)識(shí)與尋訪(續(xù)【例4-3】?維數(shù)組元素與?數(shù)組的尋訪與賦值>>a_2=zeros(2,4)%創(chuàng)建2x4的全0a_200000000a_2
%注意元素的排>>a_2([25ans
Application 、數(shù)組元素的標(biāo)識(shí)與尋訪(續(xù)>>a_2([258])=[1020a_2>>a_2(:,[23])=ones(2)%雙下標(biāo)?a_2111711
Application 2.2.4、數(shù)組元素的標(biāo)識(shí)與尋訪(續(xù)ans7ans11>>a_2(:,end:-ans7
ans ans >>a_2([4a_2 >>a_2(end,[2:end-Whatisthe
Application 2.2.4、數(shù)組元素的標(biāo)識(shí)與尋訪(續(xù)【例4-4size、length函數(shù)
?size函數(shù)返回變量的?小,即變>>len=length(a)量數(shù)組的?列數(shù)
?length函數(shù)返回變量數(shù)組的最維數(shù)
Application 、數(shù)組元素的標(biāo)識(shí)與尋訪(續(xù) 雙下標(biāo)到單下標(biāo)的轉(zhuǎn)換【例4-5sub2ind函數(shù)-雙下標(biāo)轉(zhuǎn)換為單下標(biāo)>>A=[172418;222714;4613>>A(:,:,2)=A-
Application 、數(shù)組元素的標(biāo)識(shí)與尋訪(續(xù) 單下標(biāo)到雙下標(biāo)的轉(zhuǎn)換【例4-6ind2sub函數(shù)-雙下標(biāo)轉(zhuǎn)換為單下標(biāo)>>b=>>b(:)=>>IND=[345>>[I,J]=
Application Array, a x=[125x a x=[123;514;32-x=12351432- transposey= y1251 tt 45 7 k=21.50--nB=x2345678GeneratingVectorsfrom MxNmatrixof MxNmatrixof MxNmatrixofdistributednumberson
x=zeros(1,3)x= x=x x=x0.95010.2311Matrix Thematrixindicesbeginfrom1(not0(asin ThematrixindicesmustbepositiveA(-2),Error:???A(-2),Error:???Subscriptindicesmusteitherberealpositiveintegersorlogicals.Error:???IndexexceedsmatrixLOGICAL>>X=X Insteadof>>X=X123456789>>ii=ii0>>000001111ans789Concatenationof x=[12],y=[45],z=[0A=[x B=[x;14CC=[xy???Errorusing==>vertcatCATargumentsdimensionsarenot、數(shù) 數(shù)組的定在的數(shù)據(jù)類型中,向量可視?維數(shù)組,矩陣可視為?維數(shù)組,對(duì)于維數(shù)(Dimensions)超過(guò)2的數(shù)組均可視為「數(shù)組」(Multi-dimesionalArrays,簡(jiǎn)稱N-DArrays)。 Application 4Thefirstreferencesarray?A=?A=?A(:,:,2)=A(:,:,1) 14A(:,:,2)97?A(:,:,9)6 81ThesecondreferencesdimensiontheThethirdreferencesdimension0203020300000PagePage4310000100001000012.2.5、數(shù)組(續(xù)4)n將兩個(gè)?維(平面)數(shù)組疊在?起,就構(gòu)成4)頁(yè)頁(yè)
Application 、數(shù)組(續(xù) 三維數(shù)組,可對(duì)應(yīng)??XY三維坐標(biāo),如下圖所示Y(X(行
Application 2.2.5 數(shù)組(續(xù) 三維數(shù)組元素的尋址:可以(?、列、頁(yè))來(lái)確定。 以維數(shù)3×4×2的三維數(shù)組為例,其尋址?式如下圖所示:n數(shù)組A是三維數(shù)組,其A(:,:,1)代表第?頁(yè)的?維數(shù)組,A(:,:,2)代表第?頁(yè)的?維數(shù)組。
Application 、數(shù)組(續(xù) 數(shù)組的建 建立?個(gè)簡(jiǎn)單的數(shù)組,可直接命令視窗內(nèi)輸?(使用“[]”操作符)A(:,:,1)=A(:,:,1)=[1025;4187;326A(:,:,2)=[3541;2621;423A(:,:,1)
A(:,:,2)1025354634230
Application 數(shù)組(續(xù)執(zhí)行命令:whosA,得到如下結(jié)果:
doublearrayGrandtotalis24elementsusing192
Application .6 數(shù)組支持線性代數(shù)中所有的矩陣運(yùn)算 建立特有的數(shù)組運(yùn)算符,如:“等。運(yùn)含義加+相應(yīng)運(yùn)含義加+相應(yīng)元素減-相應(yīng)元素乘*矩陣點(diǎn)相應(yīng)元素冪^矩陣冪點(diǎn)相應(yīng)元素進(jìn)?冪運(yùn)左除或\或矩陣左除左點(diǎn)除或.\或A的元素被B的對(duì)應(yīng)元素Application2.2.6、算術(shù)運(yùn)算(續(xù)【例5-1】數(shù)組加減法b>>c=b-c
Application 2.2.6、算術(shù)運(yùn)算(續(xù)【例5-2】畫(huà)出y=1/(x+1)的函數(shù)曲線,x∈[0,100]plot(x,
Application 、算術(shù)運(yùn)算(續(xù)【例5-2】?成?個(gè)信號(hào):t %采樣時(shí)間點(diǎn)?成信x=sin(2*pi*t)+legend(‘x=sin(2*pi*t)+
Application 、算術(shù)運(yùn)算(續(xù)
Application 、算術(shù)運(yùn)算(續(xù)【例5-2】點(diǎn)冪“.^”舉例a 5b
a 25b
Application 、關(guān)系運(yùn)算提供了6種關(guān)系運(yùn)算符:<、>、<=、>=、==、~=(不等于2、當(dāng)兩個(gè)維數(shù)相等的矩陣進(jìn)?標(biāo)量關(guān)系進(jìn)?比較,并給出結(jié)果,形成?的0、1
Application 、關(guān)系運(yùn)算(續(xù)【例】建立5階?陣A,判斷其元素能否被3整除。A=[24,35,13,22,63;23,39,47,80,80;P100010100010000110010000090,41,P1000101000100001100100000Prem(A,3)==0%被3除,求
Application 、邏輯運(yùn)算提供了3種邏輯運(yùn)算符:&(與)、|(或)、~(非2、當(dāng)兩個(gè)維數(shù)相等的矩陣進(jìn)?比較時(shí),其相應(yīng)位置的元素按標(biāo)量關(guān)系進(jìn)?比較,并給出結(jié)果,形成?個(gè)維數(shù)與原來(lái)相同的0、1矩陣;
Application Logical==equal greater==equal greater less>=Greaterorl<=lessor isfinite(),etc...all(),?each_poseach_pos
10NaN30-
Inf ?all_pos=all_pos=?all_pos=all_pos1?pos_fin=(Mass>=0)&(isfinite(Mass))pos_fin= 1=0=【例】在[0,3π]區(qū)間,求ysinx的值。要求消去負(fù)半波,即(π,2π)區(qū)間內(nèi)的函數(shù)值置零。x=0:pi/100:3*pi;y=y1y>=0).*y;%
Application 【例】建立矩陣A,找出在[10,20]區(qū)間的元素的位置。A=[4,15,-45,10,6;56,0,17,-find(A>=10&A<=20)A - 0-0ans367
Application yf) 關(guān)于字符串 處理字符(Characters)與字符串(Strings)的相關(guān)指令?部分都放在下列 之中: 其中的「strfun」就是代表「StringFunctions」。若要查詢與字符和字符串相關(guān)的指令,可在下輸?:helpstrfun或是help
Application 2.3字符串的概念 字符(Characters)可以構(gòu)成一個(gè)字符(Strings),或字符數(shù)組(characterarray) 一個(gè)字符串是被視為一個(gè)行向量(rowvector) 字符串中的每一個(gè)字符(含空格),以其ASCII碼的形式存放于行向量中,是該字符串變量的一個(gè)元素(element)。
Application CharacterArrays Createdusingsinglequotedelimiter?str='Hithere,'str=Hi?str2=str2 EachcharacterisaseparateHithere,element(16bitsofHithere,str
1x9 Indexingsameasfornumeric2.3、字符串 用「單引號(hào)」來(lái)界定?個(gè)字符串。 可以使用直接連接多個(gè)字符串變量,得到?個(gè)新字符串變量?!纠?-2】命名字符串變量str1=‘I str2='JavaScript,and
建立字串建立字串變量str3str1 直接連接str1及str2,以建立str3I ,JavaScript,and Application StringArrayUsing[]Eachrowmust
?str='HiHithere,Hithere,
1x9sameRowseparator:semicolon(;)Columnspace/comma
?new_str=[str,'',str1]new_str=Hithere,?str2=?new_str2=[new_str;str2]new_str2=
1x192x19ForstringsofdifferentHiHi?new_str3=strvcat(str,new_str3= 2x19matrix(zeropadded)2.3、字符串 如要輸?的字符串中有單引號(hào),則由兩個(gè)連續(xù)的單引號(hào)來(lái)表示。 若要計(jì)算字符串變量的長(zhǎng)度(即組成字符串的個(gè)數(shù)),可用length指令。 【例3-2】含單引號(hào)字符串的輸ans=sentencesentence='I''vegota計(jì)算字字符串sentence的長(zhǎng)度
Application 、字符串 double指令:查看字符串變量的內(nèi)(即ASCII內(nèi)碼 char指令將ASCII內(nèi)碼轉(zhuǎn)換為字符串形式【例3-2字符串與ASCII碼的相互轉(zhuǎn)換sentencesentence='I''vegotasentenceAscii=查看的sentence2=char(sentenceAscii)%將碼恢復(fù)成 97 100 sentence2I'vegota
Application 字符串的判斷 class或ischar指令可以用來(lái)判斷?個(gè)變量的類型或它是否為字符串變量?!纠?-4】:判斷?個(gè)變量是否為字符串變量。chinesechinese今日事,今日畢out1=x=out2=out1的值%out2的值0,代x不是字符串
Application ?個(gè)字符數(shù)組變量多?字符 第?種?法是使用?維字符數(shù)組(TwoDimensionalCharacterArrays)n 必須先確認(rèn)每個(gè)字符串(即每??)的長(zhǎng)度?樣,否則就必須在短字符串結(jié)尾補(bǔ)齊空格departments=[‘ee’;‘cs’;departments=[‘ee’;‘cs’; 注意上述語(yǔ)句中空格字符的使用。departments
Application 2.3.3、?個(gè)變量多個(gè)字符串(續(xù) 用char指令多字符departments=char(‘ee’,departments=char(‘ee’,‘cs’,的使%注意空格及「, 從?維字符數(shù)組字符串時(shí),切記要使用指令來(lái)清除字符串尾部的空格字符【例3-5使用deblank命令清除字符串尾部空格departments=char('ee','cs',dept1 dept2deblank(dept1deblank指令清除尾len2=
顯示變dept1的長(zhǎng)度%顯示變dept2的長(zhǎng)度
Application 字符串的操作 strcmp指令:用于比較字符串的內(nèi)容的異同【例3-6字符串比較str1='today';str2='tomorrow';str3='today';out1=strcmp(str1,str2)%比較字符串str1和str2out1=0 %表示字符串str1和str2不同out2=strcmp(str1,str3)%比較字符串str1和str3out2=1 %表示字符串str1和str2相同 不相等返回0,相等返回
Application 字符串的操作 eval指令:Convertingfromstringsstr=['Q= Veryusefulfore.g.multipleii=str=['Q',int2str(i),'=A',int2str(i-1),'*B;']Q12= WorkingwithString String strcmp:comparewhole strncmp:comparefirst‘N’ findstr:findssubstringwithinalarger Convertingbetweennumeric&string num2str:convertfromnumerictostring str2num:convertfromstringtonumeric空數(shù)組(empty 有?維是0的數(shù)組即為空數(shù)組 空數(shù)組不占 空n最簡(jiǎn)單的空數(shù)組:0x0的矩陣n復(fù)雜的空數(shù)組:0x5or10x0例如:>>a=[];b=ones(0,5);察看空數(shù)組:>>abcorwhosab?空數(shù)組并非全0數(shù)組
Application 空數(shù)組(續(xù) 數(shù)組維數(shù)的減小 刪除數(shù)組的某列和>>a=magic(4), 刪除(2-D、3-D)數(shù)組的單個(gè)元素??式,不能刪除單個(gè)元素>>a(1, %系統(tǒng)會(huì)警告信息? %數(shù)組a將變?yōu)橄蛄?[]”同樣可以減小字符數(shù)組的維數(shù)
Application 、元胞數(shù)組(cell元胞數(shù)組(單元數(shù)組)的概念 特殊的數(shù)據(jù)類型,在?個(gè)數(shù)組中存放各種不同類型的數(shù)據(jù) 元胞數(shù)組例?CellCell1,2Cell[123
Application CellArrayforwhichtheelementsarecellsandcan arraysofdifferent?A(1,1)={[140572?A(1,2)={'Anne?A(2,1)=?A(2,2)={-Usingbraces{}topointtoelementsofcellUsingcelldispfunctiontodisplaycell元胞數(shù)組的創(chuàng)建 創(chuàng)建? 賦值語(yǔ)句 cell函數(shù) 賦值語(yǔ)句創(chuàng)建元胞數(shù)組 元胞索引(cellindexing)?格式:a(12 元胞內(nèi)容索引(contentindexing)?式格式:a{1,2}=[…]or‘…’ 直接用?括號(hào)?次把所有元素括起來(lái)b={'JamesBond',[12;34;56];pi,
Application 2.4.1元胞數(shù)組的創(chuàng)建(續(xù) Cellindexing?式創(chuàng)建元胞數(shù)組>>a(1,1)={[143;058;72>>a(1,2)={'Anne>>a(2,1)=>>a(2,2)={- 表示空元胞數(shù)組 Contentindexing?式創(chuàng)建元胞數(shù)組>>b{1,1}='JamesBond'>>b{1,2}=[12;34;5>>b{2,1}=>>b{2,2}=
Application 元胞數(shù)組的創(chuàng)建(續(xù) 元胞數(shù)組的連接Exam:連接元胞數(shù)組a、b,?成元胞數(shù)組cclearc=[ab] %orc=[a;b]c=[3x3double] 'AnneSmith'[3.0000+7.0000i][1x21>>c=[a;Result
'James [5x5
Application 2.4.1元胞數(shù)組的創(chuàng)建(續(xù) cell函數(shù)創(chuàng)建元胞數(shù)組>>b=cell(2,b>>whos Bytes cell注意:每個(gè)cell占有4個(gè)字節(jié)的空間>>b(1,3)={1:3};%orb{1,3}=
Application 顯示元胞數(shù)組的內(nèi)容 celldisp顯示元胞數(shù)組的全部?jī)?nèi)容a[3x3double] 'AnneSmith'[3.0000+7.0000i] [1x21double]>>celldisp(a)%顯示全部?jī)?nèi)容 %圖形?式顯示元胞數(shù)組的結(jié)
Application 顯示元胞數(shù)組的內(nèi)容(續(xù) 使用內(nèi)容下標(biāo)索引顯示指定元胞的數(shù)據(jù)格式:var_name{row_index或>>a{1,… %?次顯示a的全部數(shù)據(jù)…
Application 元胞數(shù)組中的內(nèi)容 直接取用元胞數(shù)組的整個(gè)元胞(單元 取用元胞數(shù)組某元胞內(nèi)的數(shù)據(jù)單位 ? 或刪除多個(gè)元
Application 元胞數(shù)組中的內(nèi)容(續(xù)上述b元胞數(shù)組的第1?、第2列元胞的內(nèi)容>>b,d=b{1,b'James [3x2 [5x5d
Application 元胞數(shù)組中的內(nèi)容元胞數(shù)組中的內(nèi)容(續(xù) b{1,2}的第3?、第1列的數(shù)據(jù)。>>e=ee5元胞數(shù)組元胞分?jǐn)?shù)據(jù):元胞數(shù)組內(nèi)容索引,再加上?般數(shù)組的索引,即:var_name{row_ind,col_ind}(r_ind,Application2.4.3元胞數(shù)組中的內(nèi)容(續(xù) 元胞數(shù)組a第1?的所有元胞。f[3x3 'Anne Exam:刪除元胞數(shù)組a第1?的所有元胞。>>a(1,:)=a[3.0000+
Note:這里使用的是元胞(cellindexing),而不是容索引(content[1x21
Applicationof
CellArrays-100010001 cellarrayisanarrayofcells.Acellcanhold100010001'Romeo,CellArrays-Forspecifiedcontent,createsamewayasarraysbutuse(curly)braces>>a={i5:-1:2'carrots';magic(2)77NaNa[0+1.0000i] [1x4double] [2x2 CellArrays-CreateemptycellarrayCellArrays-a=cell(rows,columnsa=6)a>>aaCellArrays-Variouswaystodisplaycellarray.Oneistotypevariablenamewithnotrailingsemicolon.Thisshowstoplevelofarray>>a={'AAA'2{{12;34}}>>a {1x1CellArrays-displaycelldisp()recursivelydisplayscellarray,i.e.,ifcontentacellarray,alsodisplaysitscontent>>a={'AAA'2{{12;34}}==2a{3}{1}{1,1}==2a{3}{1}{1,1}==3=2=4cellwithinCellArrays-displaycellplot()displaysinfigurewindowdrawingof1Dor2Dcellarray>>a={'AAA'2{{12;34}}12342>>cellplot(12342CellArrays-Twotypesofindexingintoacell Cellindexing-accessgroupsofcellsbutnottheircontent Contentindexing-accesssinglecell'sCellCellArrays-Cell Donebyusingparenthesesaroundsubscript,e.g.,a(5),b(3:6,:),c(2,9) Canaccessoneormore CannotaccesscontentofUsecellindexingifyouwanttomanipulatecellsofanarray,regardless ofwhatisinside CellArrays-Todeleteelementsofacellarray,useindexing>>a={'r1c1''r1c2'3;[12;34]1:4''a=[2x2
[1x4 '>>a(:,2)=[]%deleteseconda= [2x2 '>>a(2,:)=[]%deleteseconda= CellArrays-Content Donebyusing(curly)bracesaroundsubject,e.g.,a{5},b{2,9} Letsyouaccesswhat'sinsideasinglecell Canonlyuseononecellatatime(sortof-willdiscussthislater)UsecontentindexingifyouwanttogetinsidecellCellArrays-Principal Indexingacell(s)with()alwaysproduces Indexingacellwith{}producesadatatypeofwhateverisinsidetheindexedcell Resultof{}indexingisacellonlyifcontentisanIfhavecellsindexedwith()onleftsideof=,musthavearrayofcellsofsamesizeonrightnIfarrayonleftnotsubscripted,canuse()or{}onrightCellArrays-Examples-follow>>a={'AAA'{{134}}a= >>whos Bytes 526
"Attributes"columnalwaysemptyfortheseslidessowillomitfromnowonEventhoughaisacellarray,outputfromfirstlineisshowingcontentofarray'scells 'AAA'meansthatthecontentofcell1ofaisacharacterarraywiththreeelements [2]meansthatthecontentofcell2ofaisaarraywithoneelement(thenumber {1x1cell}meansthatthecontentofcell3ofaiscellarraywithoneCellArrays-Examples-followFroma= >>z=z=>>whos cell>>z=z=>>zz6charCellArrays-Examples-follow>>z=z=>>whos
cellWhy?>>z=z=>>whos 8doubleCellArrays-Examples-follow>>z=z={1x1cell}Thismeansacellcontaininga1x1>>whos
>>z=z={2x2>>whosz
CellArrays-Examples-follow>>bb={'B'}bb= >>b=>>whos >>b(1)=???Conversiontocellfromdoubleisnot>>b(1)= ???Conversiontocellfromcharisnot>>b(1)=
???InanassignmentA(:)=B,thenumberofelementsinAandBmustbetheCellArrays-Examples-followa={1x1>>b(1)b=>>b(1)???Conversiontocellfromcharisnot>>b(1)=b= [1x4>>b(1)=
???Conversiontocellfromdoubleisnotpossible.>>b(1)=b={1x1>>b(1)=b={2x2
[1x4double][1x4CellArrays-Examples-followStoreintosingle,content-indexedaabb={1x1>>b{1}=b={1x1>>b{1}=
[1x4b= [1x4CellArrays-Examples-followab>>b{1}=b=b=b=bCellArrays-indexingTrickycase-contentindexingofmultiplecellsnsaysyoucan'tnReallymeansthatyoucantbutundermanycircumstances,contentofallbutfirstcelldisappearnFormoreinformation,see"comma-separatedlist"inhelpCellArrays-indexingAccessingarangeofcellswithcontentindexing(curlybraces)producesacomma-separatedlist.Iftherearenelementsintherange,therewillbenmembersofthelistandthesewillbeassignedinordertotheoutputvariables.Iftherearen'tenoughoutputvariables,ignoresremaininglistdata{4:7}→data{4}data{5}data{6}[abc]=data{4:7}same[abc]=data{4}data{5}data{6}CellArrays-a= >>clear>>x=x=>>whos 6>>x=x=>>xx8CellArrays->>clearx>>[xy]=x=y=>>xyx6y8CellArrays->>xy>>[xz]x=y=z=>>xyx6y8z
CellArrays-AvoidspecifyingmorethanonecellwhencontentindexingCellArrays-Contentofacell-arrayelementisoftena(numerical)array.Youcanaccessmultiplearrayelementsofasingleelementinacellarray.returnsanarraymadeupofrowsr1throughr2andcolumnsc1throughc2oftheelementatrowmandcolumnnofthecellarrayaCellArrays->>c={'CC'7;[12;34][0+i1+0i]c[>>ans=>>ans=4CellArrays->>=1234>>ans=324CellArrays-numbersfunctionsthatusenumbersincomputationsseldomworkonnumbersthatareincells.>>c={1357c= >>
???Undefinedfunctionormethod'sum'forargumentsoftypeErrorin==>meanaty=CellArrays-However,forconvenience,numbersmayappearincells.ToconvertaCellArrays-n=cell2mat(c cisacellarraywithonly nisanumerical(double) Ifelementsofcareallscalars*,nhassamedimensionsasc*Theelements sobematrices. help cell2mat()for
CellArrays->>c={1357c= >>
???Undefinedfunctionormethod'sum'forargumentsoftypeErrorin==>meanaty=>>cNum=cell2mat(ccNum= >>mean(cNumans=CellArrays-Toconvertanarrayofnumberstoacellarray,use:c=num2cell(A Aisanumerical cisacellarrayofsamedimensionACellArrays-a=3)a816357492c=a)cCellArrays-TrySupposeyouaregiventhenamesandagesofthreeguysintwoarrays,like>>names={'John''Joe''Jeff'names= >>ages={404550ages= CellArrays-TryFindthemean>>nAges=cell2mat(agesnAges= >>mean(nAgesans=orallat>>mean(cell2mat(ages)ans=CellArrays-TryStorealldatainonecellarraywiththefirstcolumncontainingthenamesandthesecondsCellArrays-Try>>ages=[404550ages= >>cAges=num2cell(agescAges=>>guys=cell(3,2guys= CellArrays-Try>>guys(:,1)=guys= >>guys(:,2)=guys=
Candothisalittlemoreeasilybyconcatenatingthetwocellarrays.SeehelpCellArrays-functions functionswilltakeacellarrayasinput,e.g.,cell2mat(),isvector(),anddeal().Others,suchasmean(),eval(),andnot(),won't.Ifoneofthelatterfunctionscanacceptthecontentoftheelementsofthecellarrayasinput,wecanprocessthosecellswiththe functioncellfun()CellArrays-functionsEvenifafunctioncantakeacellarrayasaninput,wemaywanttoapplyafunctionthatcanacceptcell-arrayargumentstothecontentofacellarray,nottothearrayitselfFindthelengthofeachwordinastring>>c={'a''bb''cccc'c= >>ans= lengthofcellarrayc,notlengthsofcontent(1,CellArrays-functions functioncellfun()appliesaspecifiedfunctiontothecontentofeveryelementofacellCellArrays-functionsWe'lluseabasicversionofcellfun,A=cellfun(fun,C Cisacell funisafunctionthattakesexactlyoneinputvalueandproducesexactlyone,scalaroutput funmustbeabletoacceptthetypeofinputinthecellsofC,e.g.,characterarray,numericalarray,etc. AisanarrayofsamedimensionasCellArrays–function SupposeCisa3x2cellarray.YoucanthinkofthethestatementA=cellfun(fun,C)asbeing
CellArrays-functionsA=cellfun(fun,CTospecifythefunction,usetheat-sign@followedbythefunctionnamewithout IfCisacellarrayofcellfun(@length,c)findsthelengtheachofthestringsinthe IfCisacellarrayofcellfun(@isempty,c lswhether noteachcellinthearrayis
CellArrays-functionsFindthemeansoffourdata>>data={[024][-101]randn(1,1000)data=[1x3[1x3>>mean()???Undefinedfunctionormethod'sum'forinputargumentstypeErrorin==>meanat
mean()doesn'tacceptcellarraysasinput,butcontentsofeacharrayisokaybecausethosearey=sum(x)/size(x,dim);numerical>>dataMeans=cellfun(@mean,datadataMeans= >>whosdata
Bytes829632CellArrays-functionstf=isempty(C)isempty()isausefulfunctionwhichreturns1(true)ifitsinputarrayisemptyand0(false)ifthearrayisnotempty.(Anemptyarrayonethathasatleastonedimensionofsizezero,e.g.,0x0,0x5,3x7x0)CellArrays-functionsTryMakeacellarrayoffourcellswhosecontentsare'a','bb',empty({}),and'ccc'.Determineifthearrayisemptyandifeachcellisempty>>c={'a''bb'{}'cccc'c=c= c)0CellArrays-functionsTryUsethepreviousarrayandfindthelengthofthearrayandthenumberofcharactersineachstringinthe>>length(cans=c)= 4CellArrays-functionsIt'scommontowanttoknowifanyelementofacellarraymeetsacertaincondition.Dothiswiththefunction:B=any(A Aisanumericalvector(notacell Bisascalarthatis1ifanyelementofAisnotzeroand0otherwise,i.e.,ifallelementsofAarezeroany()alsoworksonmatrices.SeehelpfordetailsCellArrays-functionsTryUsethepreviousarrayanddetermineifanyofthestringshaveatleastone>>lengths=cellfun(@length,clengths= >>any(lengthsans=>>any(cellfun(@length,c) ans= CellArrays-functionsonIt'salsocommontowanttoknowifallelementsofacellarraymeetacertaincondition.DothiswiththeB=all(A Aisanumericalvector(notacell Bisascalarthatis1ifallelementsofAarenotzeroand0otherwise,i.e.,ifatleastoneelementofAiszeroall()alsoworksonmatrices.SeehelpfordetailsCellArrays-functionsTryUsethepreviousarrayanddetermineifallofthestringshaveatleastone>>lengths=cellfun(@length,clengths= >>all(lengthsans=>>all(cellfun(@length,c) ans= CellArrays-Oftenit'susefultoknowwhichcellsinacellarraymeetacertaincondition.Onewaytofindoutiswiththefunction:indexes=find(A Aisanumericalvector(notacell indexesisavect
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 項(xiàng)目申請(qǐng)報(bào)告和可行性研究報(bào)告
- 農(nóng)業(yè)遙感技術(shù)應(yīng)用實(shí)戰(zhàn)手冊(cè)
- 陵園墓地裝修設(shè)計(jì)施工合同
- 知名智能家居控制系統(tǒng)
- 家庭農(nóng)場(chǎng)農(nóng)業(yè)發(fā)展指南
- 產(chǎn)業(yè)發(fā)展 規(guī)劃
- 公司上市的可行性分析報(bào)告
- 農(nóng)業(yè)產(chǎn)業(yè)鏈質(zhì)量提升行動(dòng)指南
- 三基訓(xùn)練護(hù)理復(fù)習(xí)試題有答案(一)
- 礦業(yè)行業(yè)智能化采礦與安全管理方案
- 貴州省獸藥經(jīng)營(yíng)質(zhì)量管理規(guī)范實(shí)施細(xì)則
- 常規(guī)弱電系統(tǒng)施工單價(jià)表純勞務(wù)
- 勞動(dòng)合同(模版)4篇
- 2024-2025學(xué)年小學(xué)信息技術(shù)(信息科技)五年級(jí)下冊(cè)人教版教學(xué)設(shè)計(jì)合集
- 2024年大學(xué)試題(林學(xué))-森林經(jīng)理學(xué)考試近5年真題集錦(頻考類試題)帶答案
- 醫(yī)學(xué)教材 《婦產(chǎn)科學(xué)》第9版課件-胎兒異常與多胎妊娠
- 2025年國(guó)家公務(wù)員考試行測(cè)(地市級(jí))行政職業(yè)能力測(cè)驗(yàn)試卷與參考答案
- 【魔鏡洞察】2024藥食同源保健品滋補(bǔ)品行業(yè)分析報(bào)告
- 2024年黃河委員會(huì)招聘歷年(高頻重點(diǎn)復(fù)習(xí)提升訓(xùn)練)共500題附帶答案詳解
- 肺肉芽腫性疾病的病理診斷
- DL-T 572-2021電力變壓器運(yùn)行規(guī)程-PDF解密
評(píng)論
0/150
提交評(píng)論