Anda di halaman 1dari 4

9/10/13

Control Flow - MATLAB & Simulink


United States Accelerating the pace of engineering and science Create Account Log In Contact Us Store

Products & Services

Solutions

Academ ia

Support

User Com m unity

Events

Com pany

Documentation Center
Search R2013b Documentation
MATLAB

Trial Softw are

Product Updates

Share

Control Flow
On this page

Conditional Control if, else, switch Loop Control for, while, continue, break Program Termination return Vectorization Preallocation

Conditional Control if, else, switch


Conditional statements enable you to select at run time which block of code to execute. The simplest conditional statement is an i f statement. For example: %G e n e r a t ear a n d o mn u m b e r a=r a n d i ( 1 0 0 ,1 ) ; %I fi ti se v e n ,d i v i d eb y2 i fr e m ( a ,2 )= =0 d i s p ( ' ai se v e n ' ) b=a / 2 ; e n d i fstatements can include alternate choices, using the optional keywords e l s e i for e l s e . For example: a=r a n d i ( 1 0 0 ,1 ) ; i fa<3 0 d i s p ( ' s m a l l ' ) e l s e i fa<8 0 d i s p ( ' m e d i u m ' ) e l s e d i s p ( ' l a r g e ' ) e n d Alternatively, when you want to test for equality against a set of known values, use a s w i t c hstatement. For example: [ d a y N u m ,d a y S t r i n g ]=w e e k d a y ( d a t e ,' l o n g ' ,' e n _ U S ' ) ; s w i t c hd a y S t r i n g c a s e' M o n d a y ' d i s p ( ' S t a r to ft h ew o r kw e e k ' ) c a s e' T u e s d a y ' d i s p ( ' D a y2 ' ) c a s e' W e d n e s d a y ' d i s p ( ' D a y3 ' ) c a s e' T h u r s d a y ' d i s p ( ' D a y4 ' ) c a s e' F r i d a y ' d i s p ( ' L a s td a yo ft h ew o r kw e e k ' ) o t h e r w i s e d i s p ( ' W e e k e n d ! ' ) e n d For both i fand s w i t c h , MATLAB executes the code corresponding to the first true condition, and then exits the code block. Each conditional statement requires the e n dkeyword. In general, when you have many possible discrete, known values, s w i t c hstatements are easier to read than i fstatements. However, you cannot test for inequality between s w i t c hand c a s evalues. For example, you cannot implement this type of condition with a s w i t c h :

www.mathworks.com/help/matlab/learn_matlab/flow-control.html?s_tid=doc_12b

1/4

9/10/13

Control Flow - MATLAB & Simulink


y o u r N u m b e r=i n p u t ( ' E n t e ran u m b e r :' ) ; i fy o u r N u m b e r<0 d i s p ( ' N e g a t i v e ' ) e l s e i fy o u r N u m b e r>0 d i s p ( ' P o s i t i v e ' ) e l s e d i s p ( ' Z e r o ' ) e n d Array Comparisons in Conditional Statements It is important to understand how relational operators and i fstatements work with matrices. When you want to check for equality between two variables, you might use i fA= =B ,. . . This is valid MATLAB code, and does what you expect when Aand Bare scalars. But when Aand Bare matrices, A = = Bdoes not test if they are equal, it tests where they are equal; the result is another matrix of 0s and 1s showing element-by-element equality. (In fact, if Aand Bare not the same size, then A = = Bis an error.) A=m a g i c ( 4 ) ; A= =B a n s= 0 1 1 1 B=A ; B ( 1 , 1 )=0 ;

1 1 1 1

1 1 1 1

1 1 1 1

The proper way to check for equality between two variables is to use the i s e q u a lfunction: i fi s e q u a l ( A ,B ) ,. . . i s e q u a lreturns a scalar logical value of 1(representing t r u e ) or 0(f a l s e ), instead of a matrix, as the expression to be evaluated by the i ffunction. Using the Aand Bmatrices from above, you get i s e q u a l ( A ,B ) a n s= 0 Here is another example to emphasize this point. If Aand Bare scalars, the following program will never reach the "unexpected situation". But for most pairs of matrices, including our magic squares with interchanged columns, none of the matrix conditions A > B , A<B , or A = = Bis true for all elements and so the e l s eclause is executed: i fA>B ' g r e a t e r ' e l s e i fA<B ' l e s s ' e l s e i fA= =B ' e q u a l ' e l s e e r r o r ( ' U n e x p e c t e ds i t u a t i o n ' ) e n d Several functions are helpful for reducing the results of matrix comparisons to scalar conditions for use with i f , including i s e q u a l i s e m p t y a l l a n y

Loop Control for, while, continue, break


This section covers those MATLAB functions that provide control over program loops. for The f o rloop repeats a group of statements a fixed, predetermined number of times. A matching e n ddelineates the statements: f o rn=3 : 3 2 r ( n )=r a n k ( m a g i c ( n ) ) ; e n d r The semicolon terminating the inner statement suppresses repeated printing, and the rafter the loop displays the final result. It is a good idea to indent the loops for readability, especially when they are nested: f o ri=1 : m f o rj=1 : n H ( i , j )=1 / ( i + j ) ; e n d e n d

www.mathworks.com/help/matlab/learn_matlab/flow-control.html?s_tid=doc_12b

2/4

9/10/13

Control Flow - MATLAB & Simulink


while The w h i l eloop repeats a group of statements an indefinite number of times under control of a logical condition. A matching e n d delineates the statements. Here is a complete program, illustrating w h i l e ,i f ,e l s e , and e n d , that uses interval bisection to find a zero of a polynomial: a=0 ;f a=I n f ; b=3 ;f b=I n f ; w h i l eb a>e p s * b x=( a + b ) / 2 ; f x=x ^ 3 2 * x 5 ; i fs i g n ( f x )= =s i g n ( f a ) a=x ;f a=f x ; e l s e b=x ;f b=f x ; e n d e n d x The result is a root of the polynomial x3 - 2x - 5, namely x= 2 . 0 9 4 5 5 1 4 8 1 5 4 2 3 3 The cautions involving matrix comparisons that are discussed in the section on the i fstatement also apply to the w h i l estatement. continue The c o n t i n u estatement passes control to the next iteration of the f o rloop or w h i l eloop in which it appears, skipping any remaining statements in the body of the loop. The same holds true for c o n t i n u estatements in nested loops. That is, execution continues at the beginning of the loop in which the c o n t i n u estatement was encountered. The example below shows a c o n t i n u eloop that counts the lines of code in the file m a g i c . m , skipping all blank lines and comments. A c o n t i n u estatement is used to advance to the next line in m a g i c . mwithout incrementing the count whenever a blank line or comment line is encountered: f i d=f o p e n ( ' m a g i c . m ' , ' r ' ) ; c o u n t=0 ; w h i l e~ f e o f ( f i d ) l i n e=f g e t l ( f i d ) ; i fi s e m p t y ( l i n e )| |s t r n c m p ( l i n e , ' % ' , 1 )| |~ i s c h a r ( l i n e ) c o n t i n u e e n d c o u n t=c o u n t+1 ; e n d f p r i n t f ( ' % dl i n e s \ n ' , c o u n t ) ; f c l o s e ( f i d ) ; break The b r e a kstatement lets you exit early from a f o rloop or w h i l eloop. In nested loops, b r e a kexits from the innermost loop only. Here is an improvement on the example from the previous section. Why is this use of b r e a ka good idea? a=0 ;f a=I n f ; b=3 ;f b=I n f ; w h i l eb a>e p s * b x=( a + b ) / 2 ; f x=x ^ 3 2 * x 5 ; i ff x= =0 b r e a k e l s e i fs i g n ( f x )= =s i g n ( f a ) a=x ;f a=f x ; e l s e b=x ;f b=f x ; e n d e n d x

Program Termination return


This section covers the MATLAB r e t u r nfunction that enables you to terminate your program before it runs to completion. return r e t u r nterminates the current sequence of commands and returns control to the invoking function or to the keyboard. r e t u r nis also used to terminate k e y b o a r dmode. A called function normally transfers control to the function that invoked it when it reaches the end of the function. You can insert a r e t u r nstatement within the called function to force an early termination and to transfer control to the invoking function.

Vectorization
One way to make your MATLAB programs run faster is to vectorize the algorithms you use in constructing the programs. Where other programming languages might use f o rloops or D Oloops, MATLAB can use vector or matrix operations. A simple example involves

www.mathworks.com/help/matlab/learn_matlab/flow-control.html?s_tid=doc_12b

3/4

9/10/13
creating a table of logarithms: x=. 0 1 ; f o rk=1 : 1 0 0 1 y ( k )=l o g 1 0 ( x ) ; x=x+. 0 1 ; e n d A vectorized version of the same code is x=. 0 1 : . 0 1 : 1 0 ; y=l o g 1 0 ( x ) ;

Control Flow - MATLAB & Simulink

For more complicated code, vectorization options are not always so obvious.

Preallocation
If you cannot vectorize a piece of code, you can make your f o rloops go faster by preallocating any vectors or arrays in which output results are stored. For example, this code uses the function z e r o sto preallocate the vector created in the f o rloop. This makes the f o rloop execute significantly faster: r=z e r o s ( 3 2 , 1 ) ; f o rn=1 : 3 2 r ( n )=r a n k ( m a g i c ( n ) ) ; e n d Without the preallocation in the previous example, the MATLAB interpreter enlarges the rvector by one element each time through the loop. Vector preallocation eliminates this step and results in faster execution. Was this topic helpful?

Yes

No

Try MATLAB, Simulink, and Other Products


Get trial now

1994-2013 The MathWorks, Inc.

Site Help

Patents

Trademarks

Privacy Policy

Preventing Piracy Join the conversation

www.mathworks.com/help/matlab/learn_matlab/flow-control.html?s_tid=doc_12b

4/4

Anda mungkin juga menyukai