You are on page 1of 20

CHNG 1: MATLAB C BN

1.CCTONTCBNCAMATLAB
1.Cctontcbn:Matlablmtphnmmcaocpdnggiiccbi
ton.khingMATLABtabmpvoiconcan.CcfileMATLAB
c dng *.m v ch chy trong mi trng MATLAB. MATLAB x l s liu
nhlmatrn.Khitanhlnhvocaslnh,nscthihnhngayv
kt qu hin ln mn hnh. Nu ta khng mun cho kt qu hin ln mn
hnhthsaulnhtatthmdu;.Nulnhqudi,khngvamtdng
dngcthnhlnhtrnnhiudngvcuimidngtthmdu...ri
xungdng.Khisontholnhtacthdngccphmtt:

CtrlP gililnhtrc

CtrlN gilnhsau
CtrlB lilimtkt
CtrlF tinlnmtkt
Ctrl CtrlR sangphimtt
Ctrl CrtlL sangphimtt
home CtrlA vudng
end CtrlE vcuidng
esc CtrlU xodng
del CtrlD xokttichconnhyng

backspace CtrlH xokttrcchconnhyng

)CcphptoncbncaMATLABgm:

cng

tr

nhn

chiaphi

chiatri

lutha

chuynvmatrnhaysphclinhp

)Cctontquanh:

< nhhn

<= nhhnhaybng

> lnhn

>= lnhnhocbng

== bng
1

~= khngbng
)Cctontlogic:
&

v
|

or
~

not
)Cchng:

pi 3.14159265

i so

j tngti

eps sais252

realmin sthcnhnht21022

realmax sthclnnht21023

inf vcngln

NaN
Notanumber

2. Nhp xut d liu t dng lnh: MATLAB khng i hi phi khai bo


bin trc khi dng. MATLAB phn bit ch hoa v ch thng. Cc s
liuavomitrnglmviccaMATLABclulisutphinlm
vicchonkhigplnhclearall.MATLABchophptanhpsliutdng
lnh.Khinhpmatrntbnphmtaphituntheoccquynhsau:

ngncchccphntcamatrnbngdu,haydutrng

dngdu;ktthcmthng

baoccphntcamatrnbngcpdungocvung[]
nhpccmatrnsau:

1 2 4
1
A = 3 2 5
B = 1 4 2 1
C = 4
1 5 3
7

tadngcclnh:

A=[123;324;153]

B=[1421]
C=[1;4;7]

3.Nhpxutdliutfile:MATLABcthxlhaikiufiledliu:file
2

nhphn *.matvfileASCII *.dat.luccmatrnA,B,Cdidngfile


nhphntadnglnh:

saveABCABC

vnpliccmatrnA,Bbnglnh:

loadABCAB

NumunlusliucamatrnBdidngfileASCIItavit:

saveb.datB/ascii

Tavitchngtrnhct1_1.mnhsau:

clear
A=[123;456]
B=[3;2;1];
C(2)=2;C(4)=4
disp(Nhanphimbatkydexemnhap/xuatdulieutufile)
saveABCABC%luuA,B&CduoidangMATfilecotenABC.mat
clear(A,C)%xoaAvaCkhoibonho
loadABCAC%docMATfiledenhapAvaCvaobonho
saveb.datB/ascii%luuBduoidangfileASCIIcotenb.dat
clearB
loadb.dat%docASCII
b
x=input(Nhapx:)
formatshorte
x
formatrat,x
formatlong,x
formatshort,x

4. Nhp xut d liu t bn phm: Lnh input cho php ta nhp s liu t
bnphm.Vd:

x=input(Nhapx:)

Lnhformatchophpxcnhdngthccadliu.Vd:

formatrat%sohuuti
formatlong%sosc14chusosaudauphay
formatlonge%sodangmu
formathex%sodanghex
formatshorte%sodangmungan
formatshort%trovesodangngan(default)

Mtcchkhchinthgitrcabinvchuilnhtnbinvocas
lnh MATLAB. Ta cng c th dng disp v fprintf hin th cc bin. V
d:

disp(Trisocuax=),disp(x)

Tavitchngtrnhct1_2.mnhsau:

clc
f=input(NhapnhietdoFahrenheit[F]:);
c=5/9*(f32);
fprintf(%5.2f(doFahrenheit)la%5.2f(doC).\n,f,c)
fid=fopen(ct1_2.dat,w);
fprintf(fid,%5.2f(doFahrenheit)la%5.2f(doC).\n,f,c);
fclose(fid);

Trongtrnghptamunnhpmtchuitbnphm,tacnphithmk
tsvois.Vd:

ans=input(Bantraloi<co>hoac<khong>:,s)

5.Cchmtonhc:

a.Cchmtonhccbn:

exp(x) hm e x

sqrt(x) cnbchaicax

log(x) logarittnhin
4

log10(x) logaritcs10
abs(x) moduncasphcx
angle(x) argumentcasphca
conj(x) sphclinhpcax
imag(x) phnocax
real(x) phnthccax
sign(x) ducax
cos(x)
sin(x)
tan(x)
acos(x)
asin(x)
atan(x)
cosh(x)
coth(x)
sinh(x)
tanh(x)
acosh(x)
acoth(x)
asinh(x)
atanh(x)
b.Cchmtonhctto:MATLABchophptatohmtonhcv
lunvomtfiledngnhlhmcsncaMATLAB.Vdtacnto
hm:
1

f1 (x) =
1 + 8x 2
vhm:

x12 + 4x 22 5
f1 (x1 ,x 2 )

f2 (x) =
=
2x 2 2x 3x 2.5
f
(x
,x
)
2
1
2

1
1
2

Munthtatorafilef1.mnhsau:

functiony=f1(x)
y=1./(1+8*x.^2);

vfilef2.m:
5

functiony=f2(x)
y(1)=x(1)*x(1)+4*x(2)*x(2)5;
y(2) = 2*x(1)*x(1)-2*x(1)-3*x(2) -2.5;

Khinhplnhf1(2)tacgitrcahmf1tix=2.Khinhplnhf2([24])ta
cgitrcahmf2tix1=2vx2=4.Lnh feval(f1, 2)v feval(f2,[24])
cngchoktqutngt.
Cchthhaibiudinmthmtonhcmtbintrndnglnhl
toramtitnginlinetmt biuthcchui. Vdtacthnhpt
dnglnhhmnhsau:
f1=inline(1./(1+8*x.^2),x);
f1([01]),feval(f1,[01])

Tacngcthvit:

f1=1./(1+8*x.^2);
x=[01];
eval(f1)

Nuhmlathctachcnnhpmatrncchstsmcaonht.
VdviathcP4(x)=x4+4x3+2x+1tavit:

P=[14021]

nhnhaiathctadnglnh conv;chia2athctadnglnh
deconv.Muntnhtrscaathctadnglnh polyvalvlnh polyvalm
dngkhiathclmatrn.

c.Cclnhxlhm:Lnhfplotvthhmtonhcgiaccgitr
cho.Vd:

fplot(f1,[55])

gridon

Chomthmtonhcmtbin,tacthdnglnhfminbndcaMATLAB
tmcctiuaphngcahmtrongkhongcho.Vd:

f=inline(1./((x0.3).^2+0.01)+1./((x0.9).^2+0.04)6);
x=fminbnd(f,0.3,1)

Lnh fminsearch tng t hm fminbnd dng tm cc tiu a


phngcahmnhiubin.Tachm3binlutrongfilethree_var.mnh
sau:

functionb=three_var(v)

x=v(1);
y=v(2);
z=v(3);
b=x.^2+2.5*sin(y)z^2*x^2*y^2;

Bygitmcctiuivihmnybtutx=0.6,y=1.2vz=0.135
bngcclnh:

v=[0.61.20.135];
a=fminsearch(three_var,v)

Lnh fzero dng tm im zero ca hm mt bin. V d tm gi tr


khngcahmlncngitr0.2tavit:

f=inline(1./((x0.3).^2+0.01)+1./((x0.9).^2+0.04)6);

a=fzero(f,0.2)

Zerofoundintheinterval:[0.10949,0.264].
a=
0.1316

6.Ccphptontrnmatrnvvect:
a.Khinimchung:Gistatoraccmatrnavbbngcclnh:

a=[123;456];

b=[321];

Tacthsaichng:

A=[a;789]
B=[b;[101]]

Tontdngchuynvmtmatrnthcvchuynvlinhpmtma
trnphc.Nuchmunchuynvmatrnphc,tadngthmtont.
nghalphivit..Vd:

C=[1+2*i24*i;3+i22*j];
X=C
Y=C.

b. Ch s: Phn t hng i ct j ca ma trn mn c k hiu l A(i, j).


Tuynhintacngcththamchiutiphntcamngnhmtchs,v
dA(k)vik=i+(j1)m.Cchnythngdngthamchiuvecthng
hayct.Trongtrnghpmatrnythncxemlmatrnmtct
di to t cc ct ca ma trn banu. Nh vy vitA(5) c ngha l tham
chiuphntA(2,2).

xcnhkchthccamtmatrntadnglnhlength(trvkch
thclnnht)haysize(shngvct).Vd:

c=[1234;5678];

length(c)

[m,n]=size(c)

c.Tont::Tont:lmttontquantrngcaMATLAB.N
xuthinnhiudngkhcnhau.Vd:

1:10

tomtvecthngcha10snguynt1n10.Lnh:

100:7:50

tomtdyst100n51,gim7miln.Lnh:

0:pi/4:pi

tomtdyst0npi,cchunhaupi/4
Ccbiuthcchsthamchiutimtphncamatrn.VitA(1:k,j)
l tham chiu n k phn t u tin ca ct j. Ngoi ra ton t : tham
chiutittcccphntcamthnghaymtct.Vd:

B=A(:,[132])

toramatrnBtmatrnAbngcchithtccctt[123]thnh
[132]

d.Tomatrnbnghmcsn:MATLABcungcpmtshmto
ccmatrncbn:

zeros toramatrnmccphntulzeros

z=zeros(2,4)

ones toramatrnmccphntul1

x=ones(2,3)
y=5*ones(2,2)

rand toramatrnmccphntngunhinphnbu

d=rand(4,4)

randn toramatrnmccphntngunhinphnbtrcgiao

e=randn(3,3)

magic(n)toramatrncpngmccsnguynt1nn2vitng
cchngbngtngccctnphilnhnhaybng3.
pascal(n)toramatrnxcnhdngmccphntlyttamgic
Pascal.

pascal(4)

eye(n)tomatrnnv

eye(3)
eye(m,n)tomatrnnvmrng

eye(3,4)

e.Lpghp:Tacthlpghp(concatenation)ccmatrncsnthnh
mtmatrnmi.Vd:

a=ones(3,3)
b=5*ones(3,3)
c=[a+2;b]

f.Xohngvct:Tacthxohngvcttmatrnbngdngdu
[].xoctth2camatrnbtavit:

b(:,2)=[]

Vit x(1:2:5)=[]nghaltaxoccphntbtutnphntth5v
cch2rispxplimatrn.

g.Cclnhxlmatrn:

Cng :X=A+B

Tr :X=AB

Nhn :X=A*B

:X.*Anhnccphnttngngvinhau

Chia :X=A/BlcX*B=A

:X=A\BlcA*X=B

:X=A./Bchiaccphnttngngvinhau

Lutha :X=A^2

:X=A.^2

Nghcho :X=inv(A)

nhthc :d=det(A)
7. To s ngu nhin: MATLAB c cc lnh to s ngu nhin l rand v
randntoraccsngunhintheophnbGauss.

rand(m,n)toramatrnccsngunhinphnbngnht.

randn(m,n)toramatrnccsngunhintheophnbchunGauss.

rand(3,3)
10

randn(3,3)

8.Cclnhdnglptrnh:
a.Ccphtbiuiukinif,else,elseif:
Cphpcaif:

if<biuthciukin>

<phtbiu>

end
Nu<biuthciukin>choktqungthphnlnhtrongthncaif
cthchin.

Ccphtbiuelsevleseifcngtngt.

Vd:Taxtchngtrnh)ct1_4.montuinhsau:

clc
disp(Xinchao!Hanhanhduoclamquen);

x=fix(30*rand);

disp(Tuoitoitrongkhoang030);

gu=input(Xinnhaptuoicuaban:);
ifgu<x

disp(Bantrehontoi);
elseifgu>x

disp(Banlonhontoi);
else

disp(Banbangtuoitoi);
end

b.switch:Cphpcaswitchnhsau:

switch<biuthc>

casen1:<lnh1>

casen2:<lnh2>

...............

casenn:<lnhn>

otherwise:<lnhn+1>

end
c.while:vnglpwhiledngkhikhngbittrcslnlp.Cphp
cannhsau:
11

while<biuthc>

<phtbiu>
end
XtchngtrnhinrachuoiXinchaolnmhnhvislnnhpt
bnphmct1_5.mnhsau:

clc
disp(xinchao);
gu=input(Nhapsolanin:);
i=0;
whilei~=gu
disp([Xinchaoi]);
i=i+1
end

d.for:vnglpfordngkhibittrcslnlp.Cphpnhsau:

for<chs>=<gitru>:<mctng>:<gitrcui>
Taxydngchngtrnhonsct1_6.m:

clc
x=fix(100*rand);
n=7;
t=1;
fork=1:7
num=int2str(n);
disp([Bancoquyendudoan,num,lan]);
disp(Socandoannamtrongkhoang0100);
gu=input(Nhapsomabandoan:);
ifgu<x
disp(Bandoannhohon);
elseifgu>x
disp(Sobandoanlonhon);
else
disp(Bandadoandung.Xinchucmung);
t=0;
break;
end
12

n=n1;
end
ift>0
disp(Bankhongdoanraroi);
numx=int2str(x);
disp([Dolaso:,numx]);
end

e.break:phtbiu breakktthcvnglp forhay whilemkhng


quantmniukinktthcvnglpthomnhaycha.

2.HOTRONGMATLAB
1.Cclnhv:MATLABcungcpmtlothmvbiudinccvects
liucngnhgiithchvinccngcongny.

plot ha2Dvisliu2trcvhngvtuyntnh

plot3
ha3Dvisliu2trcvhngvtuyntnh

polar
hotronghtocc

loglog
hovicctrclogarit

semilogx hovitrcxlogaritvtrcytuyntnh

semilogy hovitrcylogaritvtrcxtuyntnh

plotyy
hovitrcycnhnbntrivbnphi

2. To hnh v: Hm plot c cc dng khc nhau ph thuc vo cc i s


avo.Vdnuylmtvectthplot(y)toramtngthngquanh
giaccgitrcayvchscan.Nutac2vectxvyth plot(x,y)
torathquanhgiaxvy.

t=[0:pi/100:2*pi]

y=sin(t);

plot(t,y)
gridon

polar(t,y)

3.ctkiungv:Tacthdngcckiungvkhcnhaukhiv
hnh.Munthtachuynkiungvchohm plot.Tavitchngtrnh
ct1_7.mtorathhmhnhsin:

13


t=[0:pi/100:2*pi];

y=sin(t);

plot(t,y,.)%vbngngchmchm
gridon

4.ctmuvkchthcngv:ctmuvkchthcng
vtadngccthamssau:

LineWidth rngngthng,tnhbngsim

MarkerEdgeColor

mucacccnhcakhinhdu

MarkerFaceColor

mucakhinhdu

MarkerSize

kchthccakhinhdu
Mucxcnhbngccthams:

M
Mu
M
Mu
r
red
m
magenta
g
green
y
yellow
b
blue
k
black
c
cyan
w
white

Ccdngimnhduxcnhbng:

M
Kiunhdu
M
Kiunhdu
+ ducng
. im
o vngtrn
x chthp
* dusao
s hnhvung
d htkimcng
v imtamgichngxung
^ imtamgichngln
< tamgicsangtri
> tamgicsangphi
h lcgic
p nggic

Ccdngngthngxcnhbng:

M
Kiung
M
Kiung

nglin
:
ngchmchm
ngtnt
. ngchmgch

14

Taxtchngtrnhct1_8.mnhsau:
x=pi:pi/10:pi;

y=tan(sin(x))sin(tan(x));
plot(x,y,rs,LineWidth,2,MarkerEdgeColor,k,...
MarkerFaceColor,g,MarkerSize,10)

Chngtrnhnysvngcongy=f(x)cccctsau:

ngvlngtnt()

khinhduhnhvung(s),ngvmu(r)

ngvrng2point

cccnhcakhinhmuen

khinhdumugreen

kchthckhinhdu10point

5.Thmngvvothc:lmiunytadnglnh hold.Khi
tanhlnhholdonthMATLABkhngxothangc.Nthmsliu
vothminy.Nuphmvigitrcathmivtquccgitr
catrctocthnsnhlitlxch.

6.Chvccimsliu:vccimnhdumkhngnichngli
vi nhau ta dng c t ni rng khng c cc ng ni gia cc im,
nghaltagihm plotchvictmuvimnhdu.Taxtchng
trnhct1_9.mnhsau:

x=pi:pi/10:pi;

y=tan(sin(x))sin(tan(x));

plot(x,y,s,MarkerEdgeColor,k)

7. V cc im v ng: v c cc im nh du v ng ni gia
chngtacnmtkiungvkiuim.Taxtchngtrnhct1_10.m:

x=0:pi/15:4*pi;

y=exp(2*sin(x));

plot(x,y,r,x,y,ok)

dngvngcongy=f(x)cngnilin,mu.imnhdul
15

chocmuen.

8. V vi hai trc y: Lnh plotyy cho php to mt th c hai trc y. Ta


cngcthdngplotyychogitrtrnhaitrcyckiukhcnhaunhm
tinsosnh.Taxtchngtrnhct1_11.m:

t=0:900;

A=1000;

b=0.005;

a=0.005;

z2=sin(b*t);

z1=A*exp(a*t);

[haxes,hline1,hline2]=plotyy(t,z1,t,z2,semilogy,plot);

9.Vngcongvisliu3D:Nux,y,zl3vectccngdith
plot3svngcong3D.Tavitchngtrnhct1_12.m:

t=0:pi/50:10*pi;

plot3(sin(t),cos(t),t)

axissquare;

gridon

10.tccthngschotrc:Khitatomthnhv,MATLABtngchn
ccgiihntrntrctovkhongcchnhdudatrnsliudng
v.Tuynhintacthmtliphmvigitrtrntrcvkhongcch
nhdutheoring.Tacthdngcclnhsau:

axis
tliccgitrtrntrcto

axes
tomttrctomiviccctnhcmt

getvset chophpxcnhvtccthuctnhcatrctoang
c

gca trvtrctoc
MATLAB chn cc gii hn trn trc to v khong cch nh du da
trnsliudngv.Dnglnh axiscthtligiihnny.Cphp
calnh:

axis[xmin,xmax,ymin,ymax]
Taxtchngtrnhct1_13.mnhsau:

16

x=0:0.025:pi/2;
plot(x,tan(x),ro)
axis([0pi/205])

MATLABchiavchtrntrcdatrnphmvidliuvchiau.Tacth
mtcchchianhthngs xtickv ytickbngmtvecttngdn.Vd
xtchngtrnhct1_14.m:

x=pi:.1:pi;

y=sin(x);

plot(x,y)

set(gca,xtick,pi:pi/2:p);

set(gca,xticklabel,{pi,pi/2,0,pi/2,pi})

11.Ghinhnlncctrcto:MATLABcungcpcclnhghinhnln
hogm:

title
thmnhnvoho

xlabel
thmnhnvotrcx

ylabel thmnhnvotrcy

zlabel
thmnhnvotrcz

legend
thmchgiivoth

text
hinthchuivnbnvtrnhtnh

gtext
tvnbnlnhonhchut

\bf
boldfont

\it
italicsfont

\sl
obliquefont(chnghing)

\rm
normalfont
CcktcbitxemtrongStringpropertiescaHelp.
Tadngcclnh xlabel,ylabel,zlabelthmnhnvocctrcto.Ta
c th thm vn bn vo bt k ch no trn hnh v nh hm text. Ta c
chngtrnhct1_15.m:

x=pi:.1:pi;

y=sin(x);

plot(x,y)

xlabel(t=0to2\pi,Fontsize,16)

ylabel(sin(t),Fontsize,16)
17


title(\it{Giatricuasintuzeron2pi},Fontsize,16)

text(3*pi/4,sin(3*pi/4),\leftarrowsin(t)=0.707,FontSize,12)

12.nhvvnbntrnhnhv:Tacthsdngitngvnbnghi
chcctrcvtrbtk.MATLABnhvvnbntheonvdliutrn
trc.Vdvhmy=AetviA=0.25,t=0n900v=0.005tavit
chngtrnhct1_16.m:

t=0:900;

plot(t,0.25*exp(0.005*t))

plot(t,y)
text(300,.25*exp(.005*300),...
\bullet\leftarrow\fontname{times}0.25{\ite}^{0.005{\itt}}tai,...
{\itt}=300,FontSize,14)%ghichutait=300

Tham s HorizontalAlignment v VerticalAlignment nh v vn bn so vi


cctox,y,zcho.

13.hocbit:
a.Khivvng:hokhivvngbiudinsliulvecthayma

trn.MATLABcungcpcchmhokhivvng:
bar
hinthccctcamatrnm*nnhlmnhm,minhm
cnbar
barh
hinthccctcamatrnm*nnhlmnhm,minhm
cnbarnmngang
bar3
hinthccctcamatrnm*nnhlmnhm,minhm
cnbardng3D

bar3hhinthccctcamatrnm*nnhlmnhm,minhm
cnbardng3Dnmngang
Mc nh, mi phn t ca ma trn c biu din bng mt bar. Ta xt
chngtrnhct1_17.m:

y=[521

673

863

555
158];
18


bar(y)

b.Mtdliutrntrc:Tadngcchm xlabelv ylabelmt


ccdliutrntrc.Taxtchngtrnhct1_18.m:

nhdo=[2923272520232327];
ngay=0:5:35;
bar(ngay,nhdo)
xlabel(Ngay)
ylabel(Nhietdo(^{o}C))
set(gca,YLim,[1530],Layer,top)
gridon
set(gca,YLim,[1530])

Mc nh,phm vi gi tr ca trc y l t 0 n 30. xem nhit trong


khongt15n30tathayiphmvigitrcatrcy:

set(gca,YLim,[1530],Layer,top)

vtrnth,phmvigitrcatrcythayi.

c.Xpchngth:Tacthxpchngsliutrnththanhbng
cchtoramttrckhctrncngmtvtrvnhvytacmttrcyc
lpvibsliukhc.

TCE=[5154203702501351206020];

nhdo=[2923272520232327];

ngay=0:5:35;

bar(ngay,nhdo)

xlabel(Ngay)

ylabel(Nhietdo(^{o}C))

xp chng mt s liu ln mt th thanh trn, c trc th 2


cngvtrnhtrcthnhttavit:

h1=gca;
vtotrcth2vtrtrcthnhttrcnhtvbsliuth2:

h2=axes(Position,get(h1,Position));
19


plot(days,TCE,LineWidth,3)
trcth2khnggytrngichotrcthnhttavit:

set(h2,YAxisLocation,right,Color,none,XTickLabel,[])
set(h2,XLim,get(h1,XLim),Layer,top)
ghichlnthtavit:

text(11,380,Matdo,Rotation,55,FontSize,16)

ylabel(TCEMatdo(PPM))

title(Xepchongdothi,FontSize,16)
(lutrongct1_19.m)

d.hovng:Hmareahinthngcongtotmtvecthayt
mt ct ca ma trn. N v cc gi tr ca mt ct ca ma trn thnh mt
ngcongringvtyvngkhnggiangiaccngcongvtrcx.
taxtchngtrnhct1_20.m:

Y=[512

837

968

555

423];

area(Y)

hinththc3vng,mivngmtct.caocamithvngl
tngccphnttrongmthng.Mingcongsausdngngcong
trclmcs.hinthngchialitadnglnh:

set(gca,Layer,top)

set(gca,XTick,1:5)

gridon

f. th pie: th pie hin th theo t l phn trm ca mt phn t


camtvecthaymtmatrnsovitngccphnt.Cclnh pie v pie3
torath2Dv3D.taxtchngtrnhct1_21.m:

X=[19.3 22.1 51.6;

34.2 70.3 82.4;

61.4 82.9 90.8;


20

You might also like