You are on page 1of 57

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

50.5 54.9 59.1;

29.4 36.3 47.0];

x=sum(X);

explode=zeros(size(x));

[c,offset]=max(x);

explode(offset)=1;

h=pie(x,explode)

%A=[136];
%pie3(A)

Khi tng cc phn t trong i s th nht bng hay ln hn 1, pie v pie3


chunhoccgitr.Nhvychovectx,miphncdintch xi / sum( xi )
vixilmtphntcax.Gitrcchunhomtphnnguynca
mivng.Khitngccphnttrongisthnhtnhhn1, piev pie3
khngchunhoccphntcavectx.Chngvmtphnpie.

x=[.19.22.41];

pie(x)

g.Lmhnhchuynng:Tacthtorahnhchuynngbng2cch

tovlunhiuhnhkhcnhauvlnlthinthchng

v v xo lin tc mt i tng trn mn hnh,mi ln v li c s


thayi.
Vicchthnhttathchinhnhchuynngqua3bc:

dnghm movieindnhbnhchomtmatrnlnnhmlu
cckhunghnh.

dnghmgetframestocckhunghnh.

dnghmmoviehinthcckhunghnh.
Sau y l v d s dng movie quan st hm fft(eye(n)).Ta to chng
trnhct1_22.mnhsau:

axisequal

M=moviein(16,gcf);

set(gca,NextPlot,replacechildren)

h=uicontrol(style,slider,position,[1001050020],Min,1,Max,16)

forj=1:16

plot(fft(eye(j+16)))
21

set(h,Value,j)

M(:,j)=getframe(gcf);

end

clf;

axes(Position,[0011]);

movie(M,30)

Bcutintohnhnhchuynnglkhignmatrn.Tuynhin
trc khi gi hm moviein, ta cn to ra cc trc to c cng kch thc
vikchthcmtamunhinthhnh.Dotrongvdnytahinthccs
liucchutrnvngtrnnvnntadnglnhaxisequalxcnht
lcctrc.Hm movieintoramatrnlncha16khunghnh.Pht
biu:

set(gca,NextPlot,replacechildren)

ngn hm plot a t l cc trc v axis normal mi khi n c gi. Hm


getframekhngistrliccimnhcatrchinhnhhnhhinc.
Mikhunghnhgmccsliutrongmtvectct.Hmgetframe(gcf)chp
tonbphntrongcamtcashinhnh.Saukhitorahnhnhtac
thchychngmtslnnhtnhvd30lnnhhmmovie(M,30).
Mtphngphpnatohnhchuynnglvvxo,nghal
vmtitnghorithayivtrcanbngcchthayitox,
yvzmtlngnhnhmtvnglp.Tacthtoracchiungkhc
nhaunhcccchxohnhkhcnhau.Chnggm:

none

MATLABkhngxoitngkhindichuyn
background
MATLABxoitngbngcchvncmu
nn

xor

MATLABchxoitng
TatoraMfilectnlct1_23.mnhsau:

A=[8/300;01010;0281];

y=[35107];

h=0.01;

p=plot3(y(1),y(2),y(3),.,...

EraseMode,none,MarkerSize,5);

axis([05025252525])
22


holdon

fori=1:4000

A(1,3)=y(2);

A(3,1)=y(2);

ydot=A*y;

y=y+h*ydot;

set(p,XData,y(1),YData,y(2),ZData,y(3))%thaydoitoado

drawnow

i=i+1;

end

13.ho3D:

a.Cclnhcbn:Lnh meshv surftoralivmt3Dtmatrn


sliu.Gimatrnsliulzmmiphntcanz(i,j)xcnhtung
camtth mesh(z)toramtlicmuthhinmtzcn surf(z)tora
mtmtcmuz.

b. th cc hm hai bin: Bc th nht th hin hm 2 bin


z=f(x,y)ltomatrnxvychacctotrongminxcnhcahm.
Hmmeshgridsbinivngxcnhbi2vectxvythnhmatrnx
vy.Sautadngmatrnnynhgihm.
Takhosthm sin(r)/r.tnhhmtrongkhong8v8theoxvy
tachcnchuynmtvectischomeshgrid:

[x,y]=meshgrid(8:.5:8);

r=sqrt(x.^2+y.^2)+0.005;

matrnrchakhongcchttmcamatrn.Tiptheotadnghm mesh
vhm.

z=sin(r)./r;

mesh(z)

c.thngngmc:Cchmcontourto,hinthvghichcc
ngngmccamthaynhiumatrn.Chnggm:

clabel
toccnhnsdngmatrncontourvhinthnhn
contour hin th cc ng ng mc to bi mt gi tr cho trc
camatrnZ.
23

contour3 hinthccmtngmctobimtgitrchotrcca
matrnZ.

contourf hinththcontour2Dvtmuvnggia2ccng

contourc hmcpthptnhmatrncontour
Hmmeshchinthcontourvlivsurfchinthmtcontour.

[X,Y,Z]=peaks;
contour(X,Y,Z,20)

Micontourcmtgitrgnvin.Hmclabeldnggitrnyhinth
nhnngngmc2D.Matrncontourchagitrclabeldngchocc
ng contour 2D. Ma trn ny c xc nh bi contour, contour3 v
contourf.
hinth10ngngmccahmpeaktavit:

Z=peaks;

[C,h]=contour(Z,10);

clabel(C,h)

title({Caccontourconhan,clabel(C,h)})

Hmcontourfhinththngngmctrnmtmtphngvtmu
vng cn li gia cc ng ng mc. kim sot mu t ta dng hm
caxisvcolormap.Tavitchngtrnhct1_26.m:

Z=peaks;

[C,h]=contourf(Z,10);

caxis([2020])

colormapautumn;

title({Contourcotomau,contourf(Z,10)})

Cchm contour(z,n)v contour(z,v)chophptachrslngmc


contourhaymtmccontourcnvnovizlmatrnsliu,nls
ng contour v v l vec t cc mc contour. MATLAB khng phn bit
gia vec t mt phn t hay i lng v hng. Nh vy nu v l vec t
mtphntmtmtcontournmtmchm contour scoinls
lngngcontourchkhngphilmccontour.Nghal, contour(z,v)
cngnhcontour(z,n).hinthmtngngmctacnchovlmt
24

vectc2phntvichaiphntbngmcmongmun.Vdtora
mtngngmc3Dcahmpeakstavitchngtrnhct1_27.m:

xrange=3:.125:3;

yrange=xrange;

[X,Y]=meshgrid(xrange,yrange);

Z=peaks(X,Y);

contour3(X,Y,Z)

hinthmtmcZ=1,tachovl[11]

v=[11]

contour3(X,Y,Z,v)

Hm ginputchophptadngchuthayccphmmitnchncc
imv.Ntrvtocavtrcontr.Vdsausminhhoccdng
hmginputvhmsplinetorangcongnisuyhaibin.
TatomtMfilectnct1_28.mnhsau:

disp(Chuotphaitrocacdiemtrenduongve)

disp(Chuottraitrodiemcuoicuaduongve)

axis([010010])

holdon

x=[];

y=[];

n=0;

but=1;

whilebut==1

[xi,yi,but]=ginput(1);

plot(xi,yi,go)

n=n+1;

x(n,1)=xi;

y(n,1)=yi;

end

t=1:n;

ts=1:0.1:n;

xs=spline(t,x,ts);

25

ys=spline(t,y,ts);
plot(xs,ys,c);
holdoff

14.Vccvect:CnhiuhmMATLABdnghinthccvectchng
vvectvntc.Tanhnghamtvectbngcchdngmthay2is.
Ccismtthnhphnxvthnhphnycavect.Nutadng2i
s th i s th nht s m t thnh phn x v i s th ha m t thnh
phny.NutachdngmtisthMATLABxlnnhmtsphc,
phnthclthnhphnxvphnolthnhphny.

Cchmvvectgm:

compass vccvctbtutgctocahtocc

feather
vccvectbtutmtngthng

quiver
vccvect2Dcccthnhphn(u,v)

quiver3
vccvect3Dcccthnhphn(u,v,w)

a. Hm compass: Ta xt v d v hng v tc gi. Cc vec t xc


nhhng(gctnhbng)vtcgi(km/h)l:

hg=[45909045360335360270335270335335];
td=[668639689101412];

Tabinihnggithnhradiantrckhibininthnhto
vunggc.

hg1=hg*pi/180;
[x,y]=pol2cart(hg1,td);
compass(x,y)

vtoraghichtrnth:

gc={HuonggiovsucgiotaisanbayDaNang)
text(28,15,gc)

b.Hmfeather:Hmfeatherhinthccvectbtutmtng
thngsongsongvitrcx.Vdtoraccvectcgct900n00v
cngditavitchngtrnhct1_30.m:
theta=90:10:0;
26

r=ones(size(theta));

trckhiv,chuynccsliusangtovunggcvtnglnthnhr
dnhn:

[u,v]=pol2cart(theta*pi/180,r*10);
feather(u,v)
axisequal

Nuislsphczth feathercoiphnthclxvphnoly.Taxt
chngtrnhct1_31.m:

t=0:0.3:10;
s=0.05+i;
Z=exp(s*t);
feather(Z)

c.Hmquiver:Hmquiverhinthccvectccimchotrong
mtphng.Ccvectnycxcnhbngccthnhphnxvy.
Vdtora10contourcahmpeakstadngchngtrnhct1_32.m:

n=2.0:.2:2.0;
[X,Y,Z]=peaks(n);
contour(X,Y,Z,10)

Bygidnghmgradienttoccthnhphncavectdnglmis
choquiver:

[U,V]=gradient(Z,.2);

tholdonthmngcontour:

holdon
quiver(X,Y,U,V)
holdoff

27

d. Hm quiver3: Hm quiver3 hin th cc vec t c cc thnh phn


(u,v,w)tiim(x,y,z).Vdtabiudinquocamtvtcnmi
theot.Phngtrnhcachuynngl:
at 2
z( t) = v 0 t +

2
Tavitchngtrnhct1_33.m.Trchttagnvntcbanuvgiatca:

v0=10;%Vantocbandau
a=32;%giatoc

Tiptheotnhzticcthiim:

t=0:.1:1;
z=vz*t+1/2*a*t.^2;

Tnhvtrtheohngxvy:

vx=2;
x=vx*t;
vy=3;
y=vy*t;

Tnhccthnhphncavectvntcvhinthbngccdngquiver3:
u=gradient(x);
v=gradient(y);
w=gradient(z);
scale=0;
quiver3(x,y,z,u,v,w,scale)
axissquare

3.GIAODINHO
1.Khinimchung: tindngtacthtonngiaodinho(GUI
GraphicUserInterface)giangidngvMATLAB.Tronggiaodinnyta
cthxutdliudi2dng:vnbnvho.MimtGUIcmthay
nhiu layout(din mo). Vic to GUI to nn mt cng c ho phc v

28

nhp xut d liu mt cch trc gic, rt thun tin. Ngoi ra c th dng
GUIgimstccqutrnh,hinthccitng.
2.Nhpxutkt,sliuraGUI:
a.Tokhunghnh:Taxtcclnhsau(ct1_35.m):

f=input(Nhapnhietdo(doK):);
c=(f32)*5/9;
fprintf(1,nhietdo(doC)la:%g\n,c)

Badnglnhtrnthchincccngvicsau:

nhpgitruvo

thchinphptnhquyinhit

xutktquramnhnh
Bygitatmcchciccdnglnhtrnsaochochngthchintrn
khunkhmtkhunghocdngnhtrn
Cclnhsau(ct1_36.m)thchincngvictrn:

set(gcf,DefaultUicontrolUnit,Normalized)
frame_1=uicontrol(gcf,Style,Frame,...
Position,[0.10.10.80.3]);
frame_2=uicontrol(gcf,Style,Frame,...
Position,[0.10.60.80.3]);
set(frame_1,BackgroundColor,[0.50.50.5]);
set(frame_2,BackgroundColor,[0.50.50.5]);
29

text_f=uicontrol(gcf,Style,Text,...
String,Fahrenheit:,...
Position,[0.30.70.20.05],HorizontalAlignment,Left);
edit_f=uicontrol(gcf,Style,Edit,...
String,168.0,...
Position,[0.60.70.10.05],...
HorizontalAlignment,Right,...
Callback,ct1_38);
text_c1=uicontrol(gcf,Style,Text,...
String,Celcius:,...
Position,[0.30.30.20.05],...
HorizontalAlignment,Left);
text_c2=uicontrol(gcf,Style,Text,...
String,100.0,...
Position,[0.60.30.10.05],...
HorizontalAlignment,Left);

Bygitasxemcclnhtrnhotngnhthno.Cclnhsau:

set(gcf,DefaultUicontrolUnit,Normalized)
frame1=uicontrol(gcf,Style,Frame,...
Position,[0.10.10.80.3]);
frame2=uicontrol(gcf,Style,Frame,...
Position,[0.10.60.80.3]);
set(frame1,BackgroundColor,[0.50.50.5]);
set(frame2,BackgroundColor,[0.50.50.5]);

tohaikhunghnhchnhttrongcasFigurehinhnhvinnmuxm.
Haikhung(Frames)ctoccgcditril(0.1,0.1)v(0.1,0.6),cng
chiucao0.3nvvbrng0.8nv.nvctnhbng%cakch
cngoicaFigure.Vytacthdingiinhsau:

Khungthnhtcgctriditiimcto10%chiungang
v10%chiucaocakhungngoiFigure.

Khung th 2 c gc tri pha di ti im c to ng vi 10%


chiungangv60%chiucaocakhungngoiFigure.

Chaikhungcchiucaobng30%chiucaovbngangbng80%
bngangcakhungngoiFigure.
30

b.Dnglnheditvtextnhpxutktvsliu:Trnyta
dnglnhuicontroltovxcnhvtrhaikhunghnh.onlnhsau
sdnguicontrolvitchuiktFahrenheitlnkhungbntrn:

text_f=uicontrol(gcf,Style,Text,String,Fahrenheit:,...
Position,[0.30.70.20.05],HorizontalAlignment,Left);

Chui k t Fahrenhaeit c t vo ng v tr dn tri ca c


Positionghitrongonchngtrnhtrn.onlnhsaudngEdit vit
chuikt68.0vovtrbncnhcaFahrenheit.Chuiktcvtr
dnphitrong(PositionBox).

edit_f=uicontrol(gcf,Style,Edit,...
String,168.0,...
Position,[0.60.70.10.05],...
HorizontalAlignment,Right,...
Callback,ct1_38);

Dosdngedit,chuikt68.0lchuicthvitlictrctiptrn
GUI.Saukhinhnnttrn,gitrmivitlictipnhnvMATLABs
gilnhvittrongphncallbackct1_38.m.

Cuicngtacnphidnguicontroltotachuitext,hinthchui
Celciusv20.0trongkhungbndi.

text_c1=uicontrol(gcf,Style,Text,String,Celcius:,...
Position,[0.30.30.20.05],HorizontalAlignment,Left);
text_c2=uicontrol(gcf,Style,Text,String,20.0,Position,...
[0.60.30.10.05],HorizontalAlignment,Left);

c. T ng cp nht gi tr ln GUI: hon thin v d GUI ta thc


hinchngtrnhvinhimvtnhquyitKsangCvtng
in kt qu vo cc bn cnh chui Celcius. on m sau phc v mc
chcallback(hontrgitr)cluvofile ct1_38.mvcnidungnh
sau:
f=get(edit_f,String);
f=str2num(f);
c=(f32)*5/9;
31

c=num2str(c);
set(text_c2,String,c);

onmtrnnhngitrdolnhuicontroleditcvodidngchui
(string)vsau:
binitdngstringsangdngs
tnhquyitnhitfahrenheitsangnhitcelcius
binitssangstring
xutktqudidngstringraGUInhtext_c2

3.Nhpsliutthanhtrt:Ngoicchnhpsliutbnphm,tacth
nhpsliutthanhtrt.Tamuntoramtgiaodinnhsau:

Trong giao din ny, con trt s lm thay i gi tr nhit ua vo v


nhitquyitnhtheoCcngsthayitngng.Cclnhtora
giaodinny(ct1_37.m)l:

set(gcf,DefaultUicontrolUnit,Normalized)
frame_1=uicontrol(gcf,Style,Frame,Position,[0.10.10.80.3]);
frame_2=uicontrol(gcf,Style,Frame,Position,[0.10.60.80.3]);
set(frame_1,BackgroundColor,[0.50.50.5]);
set(frame_2,BackgroundColor,[0.50.50.5]);
text_f=uicontrol(gcf,Style,Text,String,Fahrenheit:,Position,...
[0.30.70.20.05],HorizontalAlignment,Left);
edit_f=uicontrol(gcf,Style,Edit,...
String,168.0.,,,
32

Position,[0.60.70.10.05],...
HorizontalAlignment,Right,...
Callback,ct1_38);
text_c1=uicontrol(gcf,Style,Text,...
String,Celcius:,...
Position,[0.30.30.20.05],...
HorizontalAlignment,Left);
text_c2=uicontrol(gcf,Style,Text,...
String,100.0,...
Position,[0.60.30.10.05],...
HorizontalAlignment,Left);
slider_f=uicontrol(gcf,Style,Slider,...
Min,32.0,Max,212.0,...
Value,68.0,...
Position,[0.60.80.20.05],...

Callback,ct1_39;ct1_38);

tothanhtrttadnglnh:

slider_f=uicontrol(gcf,Style,Slider,Min,32.0,Max,212.0,...
Value,68.0,Position,[0.60.80.20.05],...

Callback,ct1_39;ct1_38);

NhvyCallbackcthgimtchuicclnhMATLAB,phncchnhau
bngduchmthanhayduphy.Chuicallbackgict1_39.m:

f=get(slider_f,Value);
f=num2str(f);
set(edit_f,String,f,CallBack,ct1_40;ct1_38);

vitcdngnhpnhitgitiValuecaslider_fvovtrbncnh
chachuiFahrenheit.SauCallbackgitipct1_38.mtnhquyi
gitrnhitvgnvocnhchuiCelcius.Filect1_40.mnhsau:

f=get(edit_f,String);
f=str2num(f);
set(slider_f,Value,f);
33


cnhimvcpnhtgitrgitiValuecaslider_frisauct1_38.m
lm nt phn vic cn li: tnh i nhit v gn vo v tr cnh cha
chuiCelcius.

4.Chnlakhixutsliu:
a. Khi nim chung: Ngoi kh nng xut d liu c nh theo kiu
stringhaykius,tacthxutdliutheomtdanhmcno.minh
ho,tatofilect1_41.mnhsau:

f=input(Nhapnhietdo:);
r=f+459.7;
c=(f32)*5/9;
k=c+273.15;
choice=input([Nhap1choRankie,2choCelcius,3choKelvin:]);
ifchoice==1
fprintf(1,Nhietdo(doR)la:%g\n,r);
elseifchoice==2
fprintf(2,Nhietdo(doC)la:%g\n,c);
elseifchoice==3
fprintf(2,Nhietdo(doC)la:%g\n,c);
end

Tcaslnh,nhplnhct1_41thMATLABshinhitvchquyi
rihinthktqu.TuynhincngcGUIcaMATLABchophptathc
hinviclachnthunlihn.Tacthchnmttrong4phngxutd
liusauy:

dngpopupmenu

dnglistbox

dngradiobutton

dngcheckbox
b.Dngpopupmenu:Tatoragiaodinnhsau:

34

Cclnhthchincngvictrn(ct1_42.m)l:

set(gcf,DefaultUicontrolUnit,Normalized)
frame_1=uicontrol(gcf,Style,Frame,...
Position,[0.10.10.80.3]);
frame_2=uicontrol(gcf,Style,Frame,...
Position,[0.10.60.80.3]);
set(frame_1,BackgroundColor,[0.50.50.5]);
set(frame_2,BackgroundColor,[0.50.50.5]);
text_f=uicontrol(gcf,Style,Text,...
String,Fahrenheit:,...
Position,[0.30.70.20.05],...
HorizontalAlignment,Left);
edit_f=uicontrol(gcf,Style,Edit,...
String,...168.0,...
Position,[0.60.70.10.05],...
HorizontalAlignment,Right,...
Callback,ct1_38);
popup_c=uicontrol(gcf,...
Style,Popupmenu,...
String,Rankine|Celcius|Kelvin,...
Value,2,...
Position,[0.30.30.20.05],...
Callback,ct1_43;ct1_45);
text_c2=uicontrol(gcf,Style,Text,...

35

String,100.0,...
Position,[0.60.30.10.05],...
HorizontalAlignment,Left);
slider_f=uicontrol(gcf,Style,Slider,...
Min,32.0,Max,212.0,...
Value,68.0,...
Position,[0.60.80.20.05],...

Callback,ct1_39;ct1_45);

KhikchchutvoPopupmenu,cbakhnngchnlasxuthin.Tip
tcnhychutvomttrong3khnng,Popupmenubinmtchcnli
n v c chn. Khi dng chut ko thanh trt frame pha trn, ta c
cgitrquyisangnvcchnhinthphadi.Trongon
mtrn,gitrValuetsnl2.KhiCallbackgict1_43.m:

choice=get(popup_c,Value);

th gi tr ca bin choice c a ti Value. Sau Callback gi tip


ct1_45.mxemktqugitrongchoice.Filect1_45.mnhsau:

f=get(edit_f,String);
f=str2num(f);
r=f+459.7;
c=(f32)*5/9;
k=c+273.15;
choice=input([Nhap1choRankie,2choCelcius,3choKelvin:]);
ifchoice==1
t=r;
elseifchoice==2
t=c;
elseifchoice==3
t=k
end
t=num2str(t);
set(text_c2,String,t);

36

Bng cch thay Popupmenu bng Radiobutton uicontrol ta c


phngnRadiobutton.Giaodinscdng:

Cclnhthchincngvicny(ct1_46.m)l:

set(gcf,DefaultUicontrolUnit,Normalized)
frame_1=uicontrol(gcf,Style,Frame,Position,[0.10.10.80.3]);
frame_2=uicontrol(gcf,Style,Frame,Position,[0.10.60.80.3]);
set(frame_1,BackgroundColor,[0.50.50.5]);
set(frame_2,BackgroundColor,[0.50.50.5]);
text_f=uicontrol(gcf,Style,Text,String,Fahrenheit:,Position,...
[0.30.70.20.05],HorizontalAlignment,Left);
edit_f=uicontrol(gcf,Style,Edit,String,168.0,Position,...
[0.60.70.10.05],HorizontalAlignment,...
Right,Callback,ct1_41);
strings=[Rankine;Celcius;Kelvine];
show=[0;1;0];
ys=[3;2;1]*0.075+0.075;
fori=1:3
radio_c(i)=uicontrol(gcf,...
Style,Radiobutton,...
37


String, strings(i),...

Value, show(i),...
Position,[0.3ys(i)0.20.05],...

Callback,ct1_47;ct1_45);
end
text_c2=uicontrol(gcf,Style,Text,String,100.0,Position,...
[0.60.30.10.05],HorizontalAlignment,Left);
slider_f=uicontrol(gcf,Style,Slider,Min,32.0,Max,212.0,...
Value,68.0,Position,[0.60.80.20.05],...

Callback,ct1_39;ct1_45);

Filect1_47.m:

fori=1:3
ifgcbo==radio_c(i)

choice=i;
set(radio_c(i),Value,1);
elseif
set(radio_c(i),Value,0);

end;
end;

onlnhtrnlmtvnglp,sosnhs(handle)Callbackthuc(gitr
do hm gcbo tr v) vi handle ca mi nt. Nt no c s trng s c
ng(turnon,Value=1)vntnokhcssbngt(turnoff,Value=0).
CuicngCallbackgict1_45.mthchinvictnhquyicchnv
hinthktqu.imkhcduynhtlkhichn,Popupmenuchchamt
phntthradiobuttoncthngthichanhiuphnt.
Cuicngtaxtphngndnglistbox.Giaodincntonhsau:

38

Ccmtoragiaodintrn(ct1_48.m)l:

set(gcf,DefaultUicontrolUnit,Normalized)
frame_1=uicontrol(gcf,Style,Frame,Position,[0.10.10.80.3]);
frame_2=uicontrol(gcf,Style,Frame,Position,[0.10.60.80.3]);
set(frame_1,BackgroundColor,[0.50.50.5]);
set(frame_2,BackgroundColor,[0.50.50.5]);
text_f=uicontrol(gcf,Style,Text,String,Fahrenheit:,Position,...
[0.30.70.20.05],HorizontalAlignment,Left);
edit_f=uicontrol(gcf,Style,Edit,String,168.0,Position,...
[0.60.70.10.05],HorizontalAlignment,...
Right,Callback,ct1_38);
listbox_c=uicontrol(gcf,...
Style,Listbox,...
String,Rankine|Celcius|Kelvin,...
Value,2,...
Position,[0.30.30.20.05],...
Callback,ct1_49;ct1_45);
text_c2=uicontrol(gcf,Style,Text,String,100.0,Position,...
[0.60.30.10.05],HorizontalAlignment,Left);
slider_f=uicontrol(gcf,Style,Slider,Min,32.0,Max,212.0,...
Value,68.0,Position,[0.60.80.20.05],...

Callback,ct1_39;ct1_45);
5.CngchotoGUI
39

a.ToGUIbngcngcho:TrnytaxemxtcchtoGUI
bng phng php th cng. Ta c th to GUI bng cng c ho. Khi
nhp lnh guide ta gi trnh ho (Graphics User Interface Development
Environment)sontholayout.Ktquutinltacmtlayoutrng
nhsau:

Sontho
Alignment

thuctnh
Chyth

Sonmenu

Vngthit
k
Ccphnt

Vicutinltathitkgiaodinmongmun.Tasdngchutko
ccphntcndngtbntrivthvolayoutrngbnphi.Tacth
dchchuynccphntnyccvtrmongmunvcnchnhbngcng
cAlignment.Vimiphnttacnxcnhthuctnhchonbngcch
bmpvophnthaybmvocngcsonthothctnh
Saukhithitkxongtalunli.LcnyMATLABtngtorafile
*.figdnglugiaodinvatovfile*.mchaccmlnhcnthchin.
Viccuicnglvitccmlnhvofile*.m.Trongqutrnhthitktac
thchythxemsaumibcthitktyucuchabngcchbm
vochyth

b.MtsvdtoGUI:

)mslnbmchut:Tathitkmtgiaodinnhsau:

40

Tamunlkhibmchut,slnbmscmvghili.Trcht
tagiguidevccmtlayoutrng.VoPropertyInspector(sontho
thuctnh)vghivoNamechuict1_52vchpnhnthuctchTagmc
nhcanlfigure1;dngFontchmcnh,cch12,bold.Tadng
EditTextghilislnbm.TavoPropertyInspectorrichnString.Ta
nhpvonychuiSolanbamchuot:0.TaghivoTagchuieditmot
v cng dng Font ch mc nh, c ch 12 v bold. Tip theo ko
PushbuttonvolayoutvsonthothuctnhchonviFontchmcnh,
c ch12,bold.TrongthuctnhStringghichuiBamchuot;ghivTag
chuipushbuttonmot.Nhvyltathitkxong.Bygitalulivi
tnlct1_52.figvct1_52.m.
Nhimvtiptheolghicclnhcnthitvofile ct1_52.m.Fileny
c MATLAB t ng to ra. Ta phi thm vo cc m lnh khi
bmchutthslnbmcthhintrnEditText.Tasghiccmlnh
nyvophn:

functionvarargout=pushbuttonmot_Callback(h,eventdata,handles,varargin)

dolnhcncthchinkhigipushbutton.Nidungcact1_52.ml:

functionvarargout=Ct1_52(varargin)
ifnargin==0

fig=openfig(mfilename,reuse);

set(fig,Color,get(0,defaultUicontrolBackgroundColor));
41

handles=guihandles(fig);
guidata(fig,handles);
ifnargout>0
varargout{1}=fig;
end

elseif
ischar(varargin{1})

try

[varargout{1:nargout}]=feval(varargin{:});

catch

disp(lasterr);

end
end
functionvarargout=pushbuttonmot_Callback(h,eventdata,handles,varargin)
persistentdem;%biendemlapersistentdenotontaigiualangoiham
ifisempty(dem)
dem=0;
end
dem=dem+1;
str=sprintf(Solanbamchuot:%d,dem);
set(handles.editmot,String,str);

)ChuynitFahrenheitsangCelcius:TathitkmtGUI
chuyninhit.Giaodincdngnhsau:

ThuctnhcaLayoutcghiName: ct1_53cnccthuctnhkhc
lmcnh.
42

Ta dng hai Frame vi cc Tag l frmmot v frame2. Cc thuc tnh


khcchpnhngitrmcnh.
Edit Text th nht c cc thuc tnh FontName: Arial, FontSize: demi,
FntWeight:demi,String:Fahrenheit,Tag:editmotcnccthuctnhkhcl
mcnh.
Edit Text th hai c cc thuc tnh FontName: Arial, FontSize: demi,
FntWeight: demi, String: trng, Tag: edithai cn cc thuc tnh khc l
mcnh.
Edit Text th ba c cc thuc tnh FontName: Arial, FontSize: demi,
FntWeight:demi,String:Celcius,Tag:editbacnccthuctnhkhclmc
nh.
Edit Text th t c cc thuc tnh FontName: Arial, FontSize: demi,
FntWeight: demi, String: trng, Tag: editbon cn cc thuc tnh khc l
mcnh.
Sau khi thit k xong, lu n vi tn ct3_18.fig. MATLAB to thm
ct1_53.m.Bygitacnvitmchon.Nhimvcaonmlkhitanhp
nhit Fahrenheit vo Edit text th hai th trong Edit Text th 4 phi
xuthingitrnhitCelciustngng.Dovynidungcact1_53.ml:

functionvarargout=Ct1_53(varargin)
ifnargin==0%LAUNCHGUI

fig=openfig(mfilename,reuse);

set(fig,Color,get(0,defaultUicontrolBackgroundColor));

handles=guihandles(fig);

guidata(fig,handles);

ifnargout>0

varargout{1}=fig;

end
elseifischar(varargin{1})

try

[varargout{1:nargout}]=feval(varargin{:});%FEVALswitchyard

catch

disp(lasterr);

end
end
functionvarargout=edithai_Callback(h,eventdata,handles,varargin)
f=get(handles.edithai,String);
43

f=str2num(f);
c=(f32)*5/9;
c=num2str(c);
set(handles.editbon,String,c);

Trongonmcnvitnmtrongon:

functionvarargout=edithai_Callback(h,evendata,handles,varargin)

CclnhkhcldoMATLABtngtora.

)Dngslidernhpsliu:Tadngvdchuyninhittrn
nhngbygisthmsliderthayinhituvo.Giaodinsc
dng:

Nhvytacn5phnt,trongcmtphntlsliderv4phn
tEditText.
Layout c thuc tnh Name: ct1_54, cn cc thuc tnh khc ta chp
nhngitrmcnh.
SlidercthuctnhMax:1.0vMin:0.0.
EditTextthnhtcthuctnhFontSize:12,FntWeight:bold,String:
Fahrenheitcnccthuctnhkhcchpnhngitrmcnh.
EditTextth2cthuctnhFontSize:12,FntWeight:bold,String:
trng.
Edit Text th 3 c thuc tnh FontSize: 12, FntWeight: bold, String:
Celcius.
44

EditTextth4cthuctnhFontSize:12,FntWeight:bold,String:

trng.(Ccthuctnhmtakhngnhcncnghalchpnhngitrmc
nh).
Layoutcluvitnct1_54.fig.

Bygitavitmchophn ct1_54.mmMATLABtngtora.
Nhimvcanlnhngitrthayitcontrt,cpnhtchoEditText
2vEditText4.Tacnidungcact1_54.m:

functionvarargout=ct1_54(varargin)
ifnargin==0

fig=openfig(mfilename,reuse);

handles=guihandles(fig);

guidata(fig,handles);

ifnargout>0

varargout{1}=fig;

end
elseifischar(varargin{1})

try

[varargout{1:nargout}]=feval(varargin{:});%FEVALswitchyard

catch

disp(lasterr);

end
end

functionvarargout=slider1_Callback(h,eventdata,handles,varargin)
f=get(handles.slider1,Value);%nhangiatritucontruot
f=f*180+32;%tinhradoFahrenheit
a=num2str(f);%bienlaithanhchuoi
set(handles.edit2,String,a);%ghivaoodoFahrenheit
b=(f32)*5/9;%doithanhdoCelcius
b=num2str(b);%doilaithanhchuoi
set(handles.edit4,String,b);%ghivaoodoCelcius

)Xutsliuclachn:Tavndngvdtrnnhngbyginhit
quy i c th c tnh theo thang nhit Kenvine, Celcius hay
45

Rankine.cthchnlatadngmttrongccphngn:Popupmenu,
Rdiobutton,ListboxhayCheckbox.GiaodinkhidngPopupmenunhsau:

NhvyltacnmtSlider,baEditTextvmtPopupmenu.Layout
cthuctnhName:ct13_55.

SlidercthuctnhMax:1vMin:0

Edit Text th nht c thuc tnh FontSize: 12, FntWeight: bold v


String:Fahrenheit.

EditTextthhaicthuctnhFontSize:12,FntWeight:boldvString
trng.
EditTextth3cthuctnhFontSize:12,FntWeight:boldvString
trng.
Popupmenu c thuc tnh FontSize: 12, FontWeight: bold. ghi vo
thuctnhStringtabmpchutvoiconcanvvit3dng:Kelvine,
CelciusvRankine.

File c lu vi tn ct1_55.fig. Vn cn li l vit m trong file


ct1_55.m.McnthchinnhngitrtSlider,xemPopupmenunoc
chnhinthnhittngng.Filect1_55.mnhsau:

functionvarargout=ct1_55(varargin)
ifnargin==0%LAUNCHGUI

fig=openfig(mfilename,reuse);

set(fig,Color,get(0,defaultUicontrolBackgroundColor));

handles=guihandles(fig);

guidata(fig,handles);
46


ifnargout>0

varargout{1}=fig;

end
elseifischar(varargin{1})

try

[varargout{1:nargout}]=feval(varargin{:});

catch

disp(lasterr);

end
end
functionvarargout=slider1_Callback(h,eventdata,handles,varargin)
f=get(handles.slider1,Value);
f=f*180+32;
a=num2str(f);
set(handles.edit2,String,a);
r=f+495.7;
c=(f32)*5/9;
k=c+273.15;
chon=get(handles.popupmenu1,Value);
ifchon==1
t=k;
elseifchon==2
t=c;
elseifchon==3
t=r;
end
t=num2str(t);
set(handles.edit3,String,t);

Tiptheotaxttrnghpdnglistbox.ThayvdngPopupmenutadng
Listbox. Cc phn t khc v thuc tnh ca n khng thay i. Thuc tnh
NamecaLayoutl ct1_56.TavoStringcaListboxvghivo3dng
Kelvine,CelciusvRankine.Giaodinnhsau:

47


Filecluvitn ct1_56.fig.Tiptheovitlnhcho ct1_56.m.Tac
filenynhsau:

functionvarargout=ct1_56(varargin)
ifnargin==

fig=openfig(mfilename,reuse);

set(fig,Color,get(0,defaultUicontrolBackgroundColor));

handles=guihandles(fig);

guidata(fig,handles);

ifnargout>0

varargout{1}=fig;

end
elseifischar(varargin{1})

try

[varargout{1:nargout}]=feval(varargin{:});

catch

disp(lasterr);

end
end
functionvarargout=slider1_Callback(h,eventdata,handles,varargin)
f=get(handles.slider1,Value);
f=f*180+32;
a=num2str(f);
set(handles.edit2,String,a);
r=f+495.7;
48

c=(f32)*5/9;
k=c+273.15;
chon=get(handles.listbox1,Value);
ifchon==1
t=k;
elseifchon==2
t=c;
elseifchon==3
t=r;
end
t=num2str(t);
set(handles.edit3,String,t);

TatiptcxtphngndngRadiobutton.Giaodincdng:

Ta dng ba Radiobutton thay cho Listbox. Radiobutton th nht c


thuc tnh FontSize: 12, FntWeight: bold v String: Rankine. Radiobutton
th 2 c thuc tnh FontSize: 12, FntWeight: bold v String: Celcius.
Radibutton th 3 c thuc tnh FontSize: 12, FntWeight: bold v String:
Kelvine. Cc phn t khc v thuc tnh ca chng vn nh c. Layout c
thuctnhName:ct1_57.LuGUIvitnct1_57.fig.

Tiptheotavitccmlnhtrongct1_57.m:
functionvarargout=ct1_57(varargin)
ifnargin==0
fig=openfig(mfilename,reuse);
set(fig,Color,get(0,defaultUicontrolBackgroundColor));
handles=guihandles(fig);
49

guidata(fig,handles);
ifnargout>0
varargout{1}=fig;
end
elseifischar(varargin{1})
try
[varargout{1:nargout}]=feval(varargin{:}); catch
disp(lasterr);
end
end
functionmutual_exclude(off)
set(off,Value,0);
functionvarargout=slider1_Callback(h,eventdata,handles,varargin)
globalchon
f=get(handles.slider1,Value);
f=f*180+32;
a=num2str(f);
set(handles.edit2,String,a);
r=f+495.7;
c=(f32)*5/9;
k=c+273.15;
ifchon==1
t=r;
elseifchon==2
t=c;
elseifchon==3
t=k;
end
t=num2str(t);
set(handles.edit3,String,t);
functionvarargout=radiobutton1_Callback(h,eventdata,handles,varargin)
global chon;
off = [handles.radiobutton2, handles.radiobutton3];
mutual_exclude(off);
chon = 1;
function varargout = radiobutton2_Callback(h, eventdata, handles, varargin)
global chon;
off = [handles.radiobutton1, handles.radiobutton3];
50

mutual_exclude(off);
chon = 2;
function varargout = radiobutton3_Callback(h, eventdata, handles, varargin)
global chon;
off = [handles.radiobutton1, handles.radiobutton2];
mutual_exclude(off);
chon = 3;
o n l nh:
function mutual_exclude(off)
set(off,'Value',0);
l m cho 3 nt l nh tr th nh m t nhm. Cc cu l nh:
off = [handles.radiobutton1, handles.radiobutton2];
mutual_exclude(off);
l m cho khi ch n m t nt Radiobutton n y th khng ch n
cng ta xt ph ng n dng Checkbox. Giao di n nh sau:

c nt khc n a. Cu i

C ng nh ph ng n dng Radiobutton, ta dng ba Checkbox.


Checkbox th nh t c thu c tnh FontSize: 12, F ntWeight: bold v String:
Rankine.
Checkbox th hai c thu c tnh FontSize: 12, F ntWeight: bold v String: Celcius.
Checkbox th ba c thu c tnh FontSize: 12, F ntWeight: bold v String: Kelvine.
Cc ph n t khc khng co g thay
i. Ta l u file v i tn ct1_58.fig. Ti p theo
ta vi t m l nh cho ct1_58.m:
function varargout = ct1_58(varargin)
if nargin = = 0
fig = openfig(mfilename,'reuse');
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
handles = guihandles(fig);
guidata(fig, handles);
51

if nargout > 0
varargout{1} = fig;
end
elseif ischar(varargin{1})
try
[varargout{1:nargout}] = feval(varargin{:}); catch
disp(lasterr);
end
end
function mutual_exclude(off)
set(off,'Value',0);
function varargout = slider1_Callback(h, eventdata, handles, varargin)
global chon
f = get(handles.slider1,'Value');
f = f*180 + 32;
a = num2str(f);
set(handles.edit2,'String',a);
r = f + 495.7;
c = (f - 32)*5/9;
k = c + 273.15;
if chon = = 1
t = r;
elseif chon = = 2
t = c;
elseif chon = = 3
t = k;
end
t = num2str(t);
set(handles.edit3,'String',t);
function varargout = checkbox1_Callback(h, eventdata, handles, varargin)
global chon;
off = [handles.checkbox2, handles.checkbox3];
mutual_exclude(off);
chon = 1;
function varargout = checkbox2_Callback(h, eventdata, handles, varargin)
global chon;
off = [handles.checkbox1, handles.checkbox3];
mutual_exclude(off);
chon = 2;
function varargout = checkbox3_Callback(h, eventdata, handles, varargin)
global chon;
off = [handles.checkbox2, handles.checkbox1];
mutual_exclude(off);
chon = 3;
) GUI c dng
ho : Ta xy d ng m t GUI dng
y=tsin(t). Giao di n nh sau:

th

h m
52

Ta dng m t Axes, b n Pushbutton


t o nn giao di n n y. Khi nh n Plot,
th c a h m y = tsin(t)
c v . Khi nh n Grid on,
th
c chia l
i. Khi
nh n Grod off, l i b xo. Nh n Close
ng
th .
Layout c thu c tnh Name: ct1_59, HandleVisibility: callback.

Cc Pushbutton u c thuc tnh FontSize: 12, FntWeight: bold v cc


Stringlcctnlnh.GUIcluvitnfilelct1_59.fig.Tiptheotason
tholnhchoct1_59.m:

functionvarargout=ct1_59(varargin)
ifnargin==0

fig=openfig(mfilename,reuse);

handles=guihandles(fig);

guidata(fig,handles);

ifnargout>0

varargout{1}=fig;

end
elseifischar(varargin{1})

try

[varargout{1:nargout}]=feval(varargin{:});%FEVALswitchyard

catch

disp(lasterr);

end
end
functionvarargout=pushbutton1_Callback(h,eventdata,handles,varargin)
gridon
functionvarargout=pushbutton2_Callback(h,eventdata,handles,varargin)
gridoff
53

functionvarargout=pushbutton3_Callback(h,eventdata,handles,varargin)
close
functionvarargout=pushbutton4_Callback(h,eventdata,handles,varargin)
t=0:0.01:20;
y=t.*sin(t);
plot(t,y);
Ti p theo ta xt m t GUI c giao di n nh sau:

Nhi m v c a GUI l v
th c a h m peaks theo cc d ng khc nhau(
mesh, surf v contour) v i cc Colormap khc nhau(hsv, hot, gray, prism, cool, winter v
summer). Vi c v cc d ng
th th c hi n nh cc Pushbutton. Vi c ch n
Colormap th c hi n nh Listbox.
Layout c thu c tnh Name: ct1_60 v thu c tnh HandleVisbility: on. Cc
Pushbutton
u c thu c tnh FontSize: 12 v F ntWeight: bold. Ta l u GUI v i tn
ct1_60.fig. M trong ct1_60.m g m:
function varargout = ct1_60(varargin)
if nargin = = 0
fig = openfig(mfilename,'reuse');
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
handles = guihandles(fig);
guidata(fig, handles);
if nargout > 0
varargout{1} = fig;
end
elseif ischar(varargin{1})
try
[varargout{1:nargout}] = feval(varargin{:});
catch
54

disp(lasterr);
end
end
function varargout = pushbutton1_Callback(h, eventdata, handles, varargin)
z = peaks(40);
chon = get(handles.listbox1,'Value');
if chon = =1
colormap(hsv(256));
elseif chon = =2
colormap(hot(256));
elseif chon = =3
colormap(gray(256));
elseif chon = =4
colormap(prism(256));
elseif chon = =5
colormap(cool(256));
elseif chon = =6
colormap(winter(256));
elseif chon = =7
colormap(summer(256));
end
mesh(z);
function varargout = pushbutton2_Callback(h, eventdata, handles, varargin)
z = peaks(40);
chon = get(handles.listbox1,'Value');
if chon = =1
colormap(hsv(256));
elseif chon = =2
colormap(hot(256));
elseif chon = =3
colormap(gray(256));
elseif chon = =4
colormap(prism(256));
elseif chon = =5
colormap(cool(256));
elseif chon = =6
colormap(winter(256));
elseif chon = =7
colormap(summer(256));
end
surf(z);
function varargout = pushbutton3_Callback(h, eventdata, handles, varargin)
z = peaks(40);
chon = get(handles.listbox1,'Value');
if chon = =1
colormap(hsv(256));
55

elseif chon = =2
colormap(hot(256));
elseif chon = =3
colormap(gray(256));
elseif chon = = 4
colormap(prism(256));
elseif chon = = 5
colormap(cool(256));
elseif chon = = 6
colormap(winter(256));
elseif chon = = 7
colormap(summer(256));
end
contour(z);

) GUI c dng ho: Ta xy dng mt GUI dng menu. Giao din


caGUInhsau:

MenuDrawgmccmenuconMesh,ContourvClose.GUIclu
trongfilect1_61.figvchngtrnhclutrongfilect1_61.m:

functionvarargout=ct1_61(varargin)
gui_Singleton=1;
gui_State=struct(gui_Name,mfilename,...
gui_Singleton,gui_Singleton,...
gui_OpeningFcn,@ct1_61_OpeningFcn,...
gui_OutputFcn,@ct1_61_OutputFcn,...
gui_LayoutFcn,[],...
56

gui_Callback,[]);
ifnargin&&ischar(varargin{1})
gui_State.gui_Callback=str2func(varargin{1});
end
ifnargout
[varargout{1:nargout}]=gui_mainfcn(gui_State,varargin{:});
else
gui_mainfcn(gui_State,varargin{:});
end
handles.output=hObject;
functionvarargout=ct1_61_OutputFcn(hObject,eventdata,handles)
varargout{1}=handles.output;
functionmnumesh_Callback(hObject,eventdata,handles)
z=peaks(40);
mesh(z);
functionUntitled_3_Callback(hObject,eventdata,handles)
z=peaks(40);
contour(z);
functionmnuclose_Callback(hObject,eventdata,handles)
clf
close
functionmnudraw_Callback(hObject,eventdata,handles)

57

You might also like