programming patterns some common matlab programming pitfalls and how to avoid them

4
Reprinted from TeMathWorks News&Notes | 2008  w w w .ma t h w o r k s . c o m 1 TeMathWorks News&Notes PROGRAMMING PATTERNS GETTING THE EXPECTED ANSWER Computer programs do exactly what you code them to do. Tis means that precise notation is crucial. Here are some particular cases. Matrix and Element-Wise Multiplication Suppose that you have two large square matrices,  A and B, and you want to multiply corresponding elements in each one. If you use  A*B, you will get a result of the expected size (the same as  A), but not the right numbers. Tis is because, instead of multiplying corresponding elements in  A and B, you have performed a matrix multiplication. o multiply the corresponding elements, you must use  A.*B. >> A = [1 2; 3 4]; B = [1 0; -1 1]; >> C = A.*B C =  1 0  -3 4 >> D = A*B D =  -1 2  -1 4 Transpose and Conjugate Transpose In MALAB, you can work with double-precision arrays t hat are either real-valued or complex, usually without applying condi- tional treatment. However, you still must write the correct code. For real-valued matrices, A' and  A.' produce identical results. For matrix operations with complex-valued arrays, the matrix transpose operator ( ') is often app ropriate. For complex ma tri- ces, this operator is the complex conjugate transpose. o avoid the conjugation of a complex matrix, use the non-conjugate transpose operator (.'). >> C= A+i*B C =  1.0000 + 1.0000i 2.0000 3.0000 - 1.0000i 4.0000 + 1.0000i >> E = C' E =  1.0000 - 1.0000i 3.0000 + 1.0000i  2.0000 4.0000 - 1.0000i >> F = C.' F =  1.0000 + 1.0000i 3.0000 - 1.0000i  2.0000 4.0000 + 1.0000i Imaginary Unit i or j MALAB defines the constants i and j as sqrt(-1), the imagi- nary unit. If you use i or j as variables in your code and the code following this usage depends on either of these constants, you could get unexpected results or an error.  Just like natural languages, programm ing languages have idioms. Mastering these nuances of syntax and me aning is essential to achieving your programming goal—whether that goal is to create a robust program or simply to get the right answer. Here are some tips and best practices to help you become uent in MATLAB ®  and achieve those go als. Some Common MATLAB Programming Pitfalls and How to Avoid Them By Loren Shure

Upload: anoop-karnik

Post on 30-Oct-2015

17 views

Category:

Documents


0 download

DESCRIPTION

book

TRANSCRIPT

Page 1: Programming Patterns Some Common MATLAB Programming Pitfalls and How to Avoid Them

7/16/2019 Programming Patterns Some Common MATLAB Programming Pitfalls and How to Avoid Them

http://slidepdf.com/reader/full/programming-patterns-some-common-matlab-programming-pitfalls-and-how-to-avoid 1/4Reprinted rom TeMathWorksNews&Notes  |  2 0 0 8  w w w . m a t h w o r k s . c o m 1

TeMathWorks News&Notes

PROGRAMMING PATTERNS

GETTING THE ExPEcTED ANSWER Computer programs do exactly what you code them to do. Tis means

that precise notation is crucial. Here are some particular cases.

Matri and Element-Wise Multipliation

Suppose that you have two large square matrices, A and B, and

you want to multiply corresponding elements in each one. I you

use A*B, you will get a result o the expected size (the same as A),

but not the right numbers. Tis is because, instead o multiplying

corresponding elements in A and B, you have perormed a matrix

multiplication. o multiply the corresponding elements, you must

use A.*B. 

>> A = [1 2; 3 4]; B = [1 0; -1 1];

>> C = A.*B

C =

1 0

-3 4

>> D = A*B

D =

-1 2

-1 4

Transpose and conjugate Transpose

In MALAB, you can work with double-precision arrays that are

either real-valued or complex, usually without applying condi-

tional treatment. However, you still must write the correct code.

For real-valued matrices, A' and A.' produce identical results.

For matrix operations with complex-valued arrays, the matrix

transpose operator (') is oten appropriate. For complex matri-

ces, this operator is the complex conjugate transpose. o avoid

the conjugation o a complex matrix, use the non-conjugate

transpose operator (.').

>> C= A+i*B

C =

1.0000 + 1.0000i 2.0000

3.0000 - 1.0000i 4.0000 + 1.0000i

>> E = C'

E =

1.0000 - 1.0000i 3.0000 + 1.0000i

2.0000 4.0000 - 1.0000i

>> F = C.'

F =

1.0000 + 1.0000i 3.0000 - 1.0000i

2.0000 4.0000 + 1.0000i

Imaginary Unit i or j

MALAB deines the constants i and j as sqrt(-1), the imagi-nary unit. I you use i or j as variables in your code and the

code ollowing this usage depends on either o these constants,

you could get unexpected results or an error.

 Just like natural languages, programming languages have idioms. Mastering these nuances o syntax and meaning is

essential to achieving your programming goal—whether that goal is to create a robust program or simply to get the right

answer. Here are some tips and best practices to help you become fuent in MATLAB® and achieve those goals.

Some Common MATLAB Programming Pitfallsand How to Avoid Them

By Loren Shure

Page 2: Programming Patterns Some Common MATLAB Programming Pitfalls and How to Avoid Them

7/16/2019 Programming Patterns Some Common MATLAB Programming Pitfalls and How to Avoid Them

http://slidepdf.com/reader/full/programming-patterns-some-common-matlab-programming-pitfalls-and-how-to-avoid 2/42 Reprinted from TeMathWorksNews&Notes  |  2 0 0 8  w w w . m a t h w o r k s . c o m

TeMathWorksNews&Notes

2

TeMathWorks News&Notes

o avoid this problem, either use diferent variable names or

clear the variables once you have used them.

>> for i=1:3

M{i} = magic(i+2)

end

M =

[3x3 double]

M =

[3x3 double] [4x4 double]

M =

[3x3 double] [4x4 double] [5x5 double]

>> clear i

command/funtion Duality 

Correct punctuation can be important in MALAB, particularly 

the use o parentheses. In MALAB, the ollowing two statements

are equivalent.

foo baz 5

foo('baz','5')

By omitting parentheses when calling a unction, you call the

unction as a command. MALAB then treats all the arguments

ollowing the unction name as string inputs. o assign the output

o a unction call to a variable, use the unctional orm o the call,

not the command version.

floating-Point comparison

he deault data type in MALAB is loating-point double-pre-

cision. Because the double-precision data type uses a inite num-

ber o bits—64—to represent numbers (53 bits or the mantissa,

or approximately 16 decimal digits), many numbers, such as

1/7, cannot be represented exactly. o compare computational

results, it is inadvisable to check or strict equality between loat-ing-point quantities. Instead, use eps(target)to obtain a result

that matches the target within an acceptable tolerance.

In the ollowing example, I’ve arbitrarily chosen 10 times the

smallest possible diference:

>> A = 1/7

 A =

0.142857142857143

>> B = 0.142857142857143

B =

0.142857142857143

>> dAB = A-B

dAB =

-1.387778780781446e-016

>> AapproxB = abs(A-B) < (10 * eps(B))

 AapproxB =

1

cREATING ROBUST PROGRAMS

It’s helpul to anticipate problems that might arise when an end-

user runs your code and program to avoid errors or incorrect cal-

culations. Here are some tools or creating robust programs.

Use MException Instead o lasterror

o ensure that your program is robust, you must capture and then

deal with potential errors. I you use the older lasterror mecha-

nism to do this, however, you risk overwriting errors that have

not yet been processed. o avoid this problem, use an MException 

object, introduced in R2007b.

Old pattern 

try

doSomething;

catch

rethrow(lasterror)

end

New pattern 

try

doSomething;

catch myException

rethrow(myException) % or throw or throwAsCaller

end

Reprinted from TeMathWorksNews&Notes  |  2 0 0 8  w w w . m a t h w o r k s . c o m

Page 3: Programming Patterns Some Common MATLAB Programming Pitfalls and How to Avoid Them

7/16/2019 Programming Patterns Some Common MATLAB Programming Pitfalls and How to Avoid Them

http://slidepdf.com/reader/full/programming-patterns-some-common-matlab-programming-pitfalls-and-how-to-avoid 3/4

Page 4: Programming Patterns Some Common MATLAB Programming Pitfalls and How to Avoid Them

7/16/2019 Programming Patterns Some Common MATLAB Programming Pitfalls and How to Avoid Them

http://slidepdf.com/reader/full/programming-patterns-some-common-matlab-programming-pitfalls-and-how-to-avoid 4/4

TeMathWorks News&Notes 

4© 2008 The MathWorks, Inc. MATLAB and Simulink are registered trademarks o The MathWorks, Inc. Seewww.mathworks.com/trademarks or a list o additional trademarks. Other product or brand names may betrademarks or registered trademarks o their respective holders.

0000v00 10/08

ResouresResoures

BLOG: Loren on the Art of MATLAB 

http://blogs.mathworks.com/nn8/loren

MATLAB HELP

www.mathworks.com/nn8/matlabdoc 

Old pattern 

D = 17.34;

doSomething;

D = single(D);

New pattern 

D = 17.34;

doSomething;

S = single(D);

Use an Output Argument with load

MALAB unctions can behave in unexpected ways i MALAB

cannot “see” that some o the names used in the program are vari-

ables. o avoid this possible conusion, use an explicit output variable with load. MALAB will then better analyze the program

and more consistently recognize which programming elements

are variables. A variable can spring into existence i you use load 

to include a dataset without speciying the variables. For example,

suppose that you have a variable named var in mydat.mat and

want to display that value rom your program.

function mydisp

load mydat

disp(var)

When you run mydisp, you get this error:

>> mydisp

??? Input argument "x" is undefined.

Error in ==> var at 55

if isinteger(x)

Error in ==> mydisp at 3

disp(var)

his error occurs because var is the name o a unction on

the MALAB path, and the MALAB analysis resolved this be-

ore running the program.

o avoid the error, use one o these two alternatives:

function mydisp1

load mydat3 var

disp(var)

function mydisp2

S = load('mydat.mat;);

disp(S.var)

In both cases, MALAB understands what the variables in the

program are (var and S) and avoids the conict with the unction

ound on the path. ■

Quik Tips

• When debugging, use clear variables (or, starting with

R2008a, clearvars) to clear the workspace. Using clear 

itsel clears breakpoints in addition to variables.

• To extract the contents from a cell in a cell array, use {}. To

treat the cell array like any other array—or example, or

reshaping—use ().

• Keep handles to graphics objects that you plan to update

later instead o depending on global state. For example, cre-

ate an axes with hAx = axes; and then use hAx instead

o gca. Using the specifc reerence is more robust in cases

when something other than your fgure window or axis has

the ocus in MATLAB.

91611v00 10/08

TeMathWorks News&Notes