Solutions
Academ ia
Support
Events
Com pany
Documentation Center
Search R2013b Documentation
MATLAB
Product Updates
Share
Control Flow
On this page
Conditional Control if, else, switch Loop Control for, while, continue, break Program Termination return Vectorization Preallocation
www.mathworks.com/help/matlab/learn_matlab/flow-control.html?s_tid=doc_12b
1/4
9/10/13
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
www.mathworks.com/help/matlab/learn_matlab/flow-control.html?s_tid=doc_12b
2/4
9/10/13
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 ) ;
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
Site Help
Patents
Trademarks
Privacy Policy
www.mathworks.com/help/matlab/learn_matlab/flow-control.html?s_tid=doc_12b
4/4