晓夜寒风 发表于 2010-1-20 15:01:24

Branching
Branching is the construction

if <condition>, <program> end

The condition is a MATLAB function usually, but not necessarily with values 0 or 1 (later I will discuss when we can vary from this requirement), and the entire construction allows the execution of the program just in case the value of condition is not 0. If that value is 0, the control moves on to the next program construction. You should keep in mind that MATLAB regards a==b and a<=b as functions with values 0 or 1.
Frequently, this construction is elaborated with

if <condition1>, <program1> else <program2> end

In this case if condition is 0, then program2 is executed.
Another variation is

if <condition1>, <program1>
elseif <condition2>, <program2>
end

Now if condition1 is not 0, then program1 is executed, if condition1 is 0 and if condition2 is not 0, then program2 is executed, and otherwise control is passed on to the next construction. Here is a short program to illustrate branching.

function b=even(n)

% b=even(n). If n is an even integer, then b=1
% otherwise, b=0.

if mod(n,2)==0,
   b=1;
   else b=0;
end

晓夜寒风 发表于 2010-1-21 09:56:20

Branching is the construction

if <condition>, <program> end

The condition is a MATLAB function usually, but not necessarily with values 0 or 1 (later I will discuss when we can vary from this requirement), and the entire construction allows the execution of the program just in case the value of condition is not 0. If that value is 0, the control moves on to the next program construction. You should keep in mind that MATLAB regards a==b and a<=b as functions with values 0 or 1.
Frequently, this construction is elaborated with

if <condition1>, <program1> else <program2> end

In this case if condition is 0, then program2 is executed.
Another variation is

if <condition1>, <program1>
elseif <condition2>, <program2>
end

Now if condition1 is not 0, then program1 is executed, if condition1 is 0 and if condition2 is not 0, then program2 is executed, and otherwise control is passed on to the next construction. Here is a short program to illustrate branching.

function b=even(n)

% b=even(n). If n is an even integer, then b=1
% otherwise, b=0.

if mod(n,2)==0,
   b=1;
   else b=0;
end

晓夜寒风 发表于 2010-1-21 09:56:55

A for loop is a construction of the form

for i=1:n, <program>, end

Here we will repeat program once for each index value i. Here are some sample programs. The first is matrix addition.


function c=add(a,b)

% c=add(a,b). This is the function which adds
% the matrices a and b. It duplicates the MATLAB
% function a+b.

=size(a);
=size(b);
if m~=k | n~=l,
   r='ERROR using add: matrices are not the same size';
   return,
end
c=zeros(m,n);
for i=1:m,
   for j=1:n,
      c(i,j)=a(i,j)+b(i,j);
   end
end

The next program is matrix multiplication.


function c=mult(a,b)

% c=mult(a,b). This is the matrix product of
% the matrices a and b. It duplicates the MATLAB
% function c=a*b.

=size(a);
=size(b);
if n~=k,
   c='ERROR using mult: matrices are not compatible
      for multiplication',
   return,
end,
c=zeros(m,l);
for i=1:m,
   for j=1:l,
      for p=1:n,
         c(i,j)=c(i,j)+a(i,p)*b(p,j);
      end
   end
end

For both of these programs you should notice the branch construction which follows the size statements. This is included as an error message. In the case of add, an error is made if we attempt to add matrices of different sizes, and in the case of mult it is an error to multiply if the matrix on the left does not have the same number of columns as the number of rows of the the matrix on the right. Had these messages not been included and the error was made, MATLAB would have delivered another error message saying that the index exceeds the matrix dimensions. You will notice in the error message the use of single quotes. The words surrounded by the quotes will be treated as text and sent to the screen as the value of the variable c. Following the message is the command return, which is the directive to send the control back to the function which called add or return to the prompt. I usually only recommend using the return command in the context of an error message. Most MATLAB implementations have an error message function, either errmsg or error, which you might prefer to use.

In the construction

for i=1:n, <program>, end

the index i may (in fact usually does) occur in some essential way inside the program. MATLAB will allow you to put any vector in place of the vector 1:n in this construction.
Thus the construction

for i=, <program>, end

is perfectly legitimate. In this case program will execute 5 times and the values for the variable i during execution are successively, 2,4,5,6,10. The MATLAB developers went one step further. If you can put a vector in, why not put a matrix in? So, for example,
for i=magic(7), <program>, end

is also legal. Now the program will execute 7 (=number of columns) times, and the values of i used in program will be successively the columns of magic(7).

晓夜寒风 发表于 2010-1-21 09:57:15

A while loop is a construction of the form

while <condition>, <program>, end

where condition is a MATLAB function, as with the branching construction. The program program will execute successively as long as the value of condition is not 0. While loops carry an implicit danger in that there is no guarantee in general that you will exit a while loop. Here is a sample program using a while loop.

function l=twolog(n)

% l=twolog(n). l is the floor of the base 2
% logarithm of n.

l=0;
m=2;
while m<=n
   l=l+1;
   m=2*m;
end

晓夜寒风 发表于 2010-1-21 09:57:35

Recursion
Recursion is a devious construction which allows a function to call itself. Here is a simple example of recursion


function y=twoexp(n)

% y=twoexp(n). This is a recursive program for computing
% y=2^n. The program halts only if n is a nonnegative integer.

if n==0, y=1;
   else y=2*twoexp(n-1);
end

The program has a branching construction built in. Many recursive programs do. The condition n==0 is the base of the recursion. This is the only way to get the program to stop calling itself. The "else" part is the recursion. Notice how the twoexp(n-1) occurs right there in the program which is defining twoexp(n)! The secret is that it is calling a lower value, n-1, and it will continue to do so until it gets down to n=0. A successful recursion is calling a lower value.

There are several dangers using recursion. The first is that, like while loops, it is possible for the function to call itself forever and never return an answer. The second is that recursion can lead to redundant calculations which, though they may terminate, can be time consuming. The third danger is that while a recursive program is running it needs extra space to accomodate the overhead of the recursion. In numerical calculations on very large systems of equations memory space is frequently at a premium, and it should not be wasted on program overhead. With all of these bad possibilities why use recursion? It is not always bad; only in the hands of an inexperienced user. Recursive programs can be easier to write and read than nonrecursive programs. Some of the future projects illustrate good and poor uses of recursion.

晓夜寒风 发表于 2010-1-21 09:58:01

Miscellaneous Programming Items
It is possible to place a matrix valued function as the condition of a branching construction or a while loop. Thus the condition might be a matrix like ones(2),zeros(2), or eye(2). How would a construction like

if <condition>, < program1>,
else <program2>, end

behave if condition=eye(2)? The program1 will execute if all of the entries of condition are not 0. Thus if condition=magic(2), program1 will execute while if condition=eye(2) control will pass to the "else" part and program2 will execute.
A problematic construction occurs when you have

if A ~= B, <program>, end.

You would like program to execute if the matrices A and B differ on some entry. Under the convention, program will only execute when they differ on all entries. There are various ways around this. One is the construction
if A ==Belse <program>, end

which will pass control to the "else" part if A and B differ on at least one entry. Another is to convert A==B into a binary valued function by using all(all(A==B)). The inside all creates a binary vector whose i--th entry is 1 only if the i--th column of A is the same as the i--th column of B. The outside all produces a 1 if all the entries of the vector are 1. Thus if A and B differ on at least one entry, then all(all(A==B))=0. The construction
if ~ all(all(A==B)), <program>, end

then behaves in the desired way.
Essentially, the same convention holds for the while construction.

while <condition>, <program>, end.

The program program will execute successively as long as every entry in condition is not 0, and the control passes out of the loop when at least one entry of condition is 0.
Another problem occurs when you have a conjunction of conditions, as in

if<condition1> & < condition2>,
<program>,end

Of course, program will execute if both condition1 and condition2 are nonzero. Suppose that condition1=0 and condition2 causes an error message. This might happen for
i<=m &A(i,j)==0

where m is the number of columns of A. If i>m, then you would like to pass the control, but since A(i,j) makes no sense if i>m an error message will be dished up. Here you can nest the conditions.

if i<=m,
   if A(i,j)==0,
      <program>
   end
end

晓夜寒风 发表于 2010-1-21 09:58:21

Scripts
A script is an m-file without the function declaration at the top. A script behaves differently. When you type who you are given a list of the variables which are in force during the current session. Suppose that x is one of those variables. When you write a program using a function file and you use the variable x inside the program, the program will not use the value of x from your session (unless x was one of the input values in the function), rather x will have the value appropriate to the program. Furthermore, unless you declare a new value for x, the program will not change the value of x from the session. This is very convenient since it means that you do not have to worry too much about the session variables while your program is running. All this has happened because of the function declaration. If you do not make that function declaration, then the variables in your session can be altered. Sometimes this is quite useful, but I usually recommend that you use function files.

晓夜寒风 发表于 2010-1-21 09:58:47

Suggestions
These are a few pointers about programming and programming in MATLAB in particular.

1) I urge you to use the indented style that you have seen in the above programs. It makes the programs easier to read, the program syntax is easier to check, and it forces you to think in terms of building your programs in blocks.

2) Put lots of comments in your program to tell the reader in plain English what is going on. Some day that reader will be you, and you will wonder what you did.

3) Put error messages in your programs like the ones above. As you go through this manual, your programs will build on each other. Error messages will help you debug future programs.

4) Always structure your output as if it will be the input of another function. For example, if your program has "yes-no" type output, do not have it return the words "yes" and "no," rather return 1 or 0, so that it can be used as a condition for a branch or while loop construction in the future.

5) In MATLAB, try to avoid loops in your programs. MATLAB is optimized to run the built-in functions. For a comparison, see how much faster A*B is over mult(A,B). You will be amazed at how much economy can be achieved with MATLAB functions.

6) If you are having trouble writing a program, get a small part of it running and try to build on that. With reference to 5), write the program first with loops, if necessary, then go back and improve it.

晓夜寒风 发表于 2010-1-21 09:59:02

MATLAB demonstrations
Matlab is shipped with a number of demonstration programs. Use help demos to find out more about these (the number of demos will depend upon the version of Matlab you have).

Some of the standard demos may be especially useful to users who are beginners in linear algebra:

demo - Demonstrate some of MATLAB's capabilities.

matdemo - Introduction to matrix computation in MATLAB.

rrefmovie - Computation of Reduced Row Echelon Form

晓夜寒风 发表于 2010-1-21 09:59:19

Some MATLAB built-in functions
This is a list of functions available in Matlab as of 1984, which should be taken as a quick reminder of the most basic tools available. See the Matlab help screens and excerpts from those screens reprinted in section Some MATLAB function descriptions. In any case, your version of Matlab may vary slightly.

intro    <      chol   end      function lu       quit   sprintf
help   >      clc      eps      global   macro    qz       sqrt   
demo   =      clear    error    grid   magic    rand   startup
[      &      clg      eval   hess   max      rcond    string   
]      |      clock    exist    hold   memory   real   subplot
(      ~      conj   exit   home   mesh   relop    sum      
)      abs      contourexp      ident    meta   rem      svd      
.      all      cos      expm   if       min      return   tan      
,      ans      cumprodeye      imag   nan      round    text   
;      any      cumsum   feval    inf      nargin   save   title   
%      acos   delete   fft      input    norm   schur    type   
!      asin   det      filter   inv      ones   script   what   
:      atan   diag   find   isnan    pack   semilogx while   
'      atan2    diary    finite   keyboard pause    semilogy who      
+      axis   dir      fix      load   pi       setstr   xlabel   
-      balancedisp   floor    log      plot   shg      ylabel   
*      break    echo   flops    loglog   polar    sign   zeros   
\      caseseneig      for      logop    prod   sin      
/      ceil   else   format   ltifr    prtsc    size   
^      chdir    elseif   fprintfltitr    qr       sort   


acosh      demo         hankel       membrane   print      table1
angle      demolist   hds          menu         quad         table2
asinh      dft          hilb         meshdemo   quaddemo   tanh   
atanh      diff         hist         meshdom      quadstep   tek   
bar          eigmovie   histogram    mkpp         rank         tek4100
bench      ergo         hp2647       movies       rat          terminal
bessel       etime      humps      nademo       ratmovie   toeplitz
bessela      expm1      idft         nelder       readme       trace   
besselh      expm2      ieee         neldstep   residue      translate
besseln      expm3      ifft         nnls         retro      tril
blanks       feval      ifft2      null         roots      triu   
cdf2rdf      fft2         info         num2str      rot90      unmkpp
census       fftshift   inquire      ode23      rratref      vdpol
citoh      fitdemo      int2str      ode45      rratrefmovie versa
cla          fitfun       invhilb      odedemo      rref         vt100
compan       flipx      isempty      orth         rsf2csf      vt240
computer   flipy      kron         pinv         sc2dc      why   
cond         funm         length       plotdemo   sg100      wow   
conv         gallery      log10      poly         sg200      xterm
conv2      gamma      logm         polyfit      sinh         zerodemo
corr         getenv       logspace   polyline   spline       zeroin
cosh         ginput       matdemo      polymark   sqrtm      
ctheorem   gpp          matlab       polyval      square      
dc2sc      graphon      mean         polyvalm   std         
deconv       hadamard   median       ppval      sun         


addtwopi buttap   cov      fftdemofreqz    kaiser   specplot
bartlett butter   decimate filtdemo fstab    numf   spectrum
bilinear chebap   denf   fir1   hammingreadme2triang   
blackman chebwindetrendfir2   hanningremez    xcorr   
boxcar   cheby    eqnerr2freqs    interp   remezddxcorr2   
                                                      yulewalk
页: 1 [2] 3 4
查看完整版本: Matlab入门(英文)

招聘斑竹