2-5 M 檔?

Yn@jq MATLAB OAiNoǫOs@ӰɦW m ɮסAæb MATLAB OܸUJɮתDɦWYiCإ]t MATLAB Oɮ׳H m ɦWA]q M ɮס]M-files^CҦp@ӦW myTest.m M ɮסA]t@sꪺ MATLAB OAunJ myTestAYiҥ]tOG

>> pwd % ܥثeu@ؿ]pwd = present working directory^ ans = C:\Users\RogerJang\Documents\MATLAB

ۧڭ̭n cd OӶiJڭ̪dɮ myTest.m ҦbؿG

>> cd d:\matlabBook\MATLAB{]pGJg\02-챴MATLAB

]pGؿ|]tŮAڭ̴Nϥέ^媺޸ӥ]ؿ|C^

Hint
poѪdҵ{GbiWzdҮɡAAqѩҪdҥФANҦdҵ{ud:matlabBookMATLAB {]pGJgvAԨФCA]iHѥѧ@̪]http://mirlab.org/jang^s쥻ѪANiHUdҵ{XC

ۧڭ̥iH myTest.m eApUG

>> type myTest.m % myTest.m e % myTest: my first test M-file. % Roger Jang, March 3, 1997 fprintf('Start of myTest.m!\n'); for i = 1:3 fprintf('i = %d ---> i^3 = %d\n', i, i^3); end fprintf('End of myTest.m!\n');

ۧڭ̴NiH myTest.mG

>> myTest % myTest.m Start of myTest.m! i = 1 ---> i^3 = 1 i = 2 ---> i^3 = 8 i = 3 ---> i^3 = 27 End of myTest.m!

Hint
Ĥ@Ѧ]H1 Help Line^GmyTest.m eOѡAiHϵ{AѻP޲zCSOnOAĤ@Ѧq`Ψ²u M ɮת\AHK lookfor Hr諸覡ӧX M ɮסC|ҨӻAmyTest.m Ĥ@Ѧ]t myTest oӦrA]pGJ lookfor myTestAMATLAB YiCXҦbĤ@Ѧ]t myTest M ɮסA]myTest.m ]|QCWbC

YӻAM ɮץiAӤZ@]Scripts^@Ψơ]Functions^C򥻤WAZ]Ҧpez myTest.m ɡ^ĥΩMNӧO MATLAB OιB⦡Ab MATLAB ROv@J@ˡA]bZɡAiHϥxsu@ŶܼơAӥBbZ]wܼơA]bu@ŶݱoCܩƫhݭnΨJ޼ơ]Input Arguments^MX޼ơ]Output Arguments^ӶǻTAoNO C yơAάO FORTRAN yƵ{ǡ]Subroutines^C|ҨӻAYnp@ӥƪ]Factorial^Aڭ̥iHg@ӦpU MATLAB ƨñNsɩ fact01.mG

>> type fact01.m function output = fact01(n) % FACT01 Calculate factorial of a given positive integer (for-loop version) output = 1; for i = 1:n, output = output*i; end

䤤 fact01 OƦW١An OJ޼ơAoutput OX޼ơA i hOƥΨ쪺ȮܼơCnϥΦơAJƦW٤ξAJ޼ƭȧYiG

>> y = fact01(5) y = 120

]MAb fact01 eAzݥiJ fact01.m ҦbؿC^b fact01(5) ɡAMATLAB |J@ӤUhȮɤu@Ŷ]Temperary Workspace^ANܼ n ȳ]w 5 AMiUɤUBAbqͪҦܼơ]]tJ޼ nBȮܼ iAHοX޼ output^|xsbȮɤu@ŶCݹB⧹AMATLAB |N̫X޼ output ȳ]wWhܼ yAñNMȮɤu@ŶΨҧtҦܼơCyܻAbIsƮɡAzugѿJ޼ƨӱƪJAgѿX޼ƨӱoƪXAҦȮܼƳ|HۨƪӮAzõLkoL̪ȡC

MATLAB Ƥ]iHOj]Recursive^A]NOA@ӨƥiHIsLC|ҨӻAn! = n*(n-1)!A]eƥiH令jgkG

>> type fact02.m function output = fact02(n) % FACT02 Calculate factorial of a given positive integer (recursive version) if n == 1, % Terminating condition output = 1; return; end output = n*fact02(n-1);

Hint
ơGeҥΨ쪺ƥuOºΨӻ MATLAB [CYڭnp@ӥ n ]Y n!^ɡAiwUCXؤ覡G
  • factorial(n)
  • prod(1:n)
  • gamma(n-1)

ȱo`NOAbg@ӻjƮɡA@wn]t]Terminating Condition^A_hƱN|@AIsۤvAiJLajAû|AqOQӺɬCHWҦӨAn==1 YAɧڭ̪N output ] 1AӤAIsƥC]Ъ`NAbIsƮɡApG n OơA@˷|iJЩIsۤvLaj餤C^

M ɮתLӸ`AŪ̥iѦҥѪĤQuM ɮסvC


MATLAB{]pGJg