23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

11 Improving Performance and Memory Usage<br />

Assigning Real and Complex Numbers<br />

Assigning a complex number to a variable that already holds a real number<br />

impacts the performance of your program. Similarly, you should not assign a<br />

realvaluetoavariablethatalreadyholdsacomplexvalue.<br />

OperatingonRealData<br />

When operating on real (i.e., noncomplex) numbers, it is more efficient to use<br />

<strong>MATLAB</strong> functions that have been designed specifically for real numbers.<br />

The following functions return numeric values that are real.<br />

Function<br />

reallog<br />

realpow<br />

realsqrt<br />

Description<br />

Find natural logarithm for nonnegative real arrays<br />

Find array power for real-only output<br />

Find square root for nonnegative real arrays<br />

Using Appropriate Logical Operators<br />

When performing a logical AND or OR operation, you have a choice of two<br />

operators of each type.<br />

Operator<br />

&, |<br />

&&, ||<br />

Description<br />

Perform logical AND and OR on arrays element by<br />

element<br />

Perform logical AND and OR on scalar values with<br />

short-circuiting<br />

In if and while statements, it is more efficient to use the short-circuiting<br />

operators, && for logical AND and || for logical OR. This is because these<br />

operators often don’t have to evaluate the entire logical expression. For<br />

example, <strong>MATLAB</strong> evaluates only the first part of this expression whenever<br />

the number of input arguments is less than three:<br />

if (nargin >= 3) && (ischar(varargin{3}))<br />

See Short-Circuit Operators in the <strong>MATLAB</strong> documentation for a discussion<br />

on short-circuiting with && and ||.<br />

11-10

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!