23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Techniques for Improving Performance<br />

This statement preallocates a 100-by-100 matrix of int8 first by creating a<br />

full matrix of doubles, and then converting each element to int8. Thiscosts<br />

time and uses memory unnecessarily.<br />

The next statement shows how to do this more efficiently:<br />

A = zeros(100, 'int8');<br />

Coding Loops in a MEX-File<br />

If there are instances where you cannot vectorize and must use a for or<br />

while loop, consider coding the loop in a MEX-file. In this way, the loop<br />

executes much more quickly since the instructions in the loop do not have to<br />

be interpreted each time they execute.<br />

See “Introducing MEX-Files” in the External Interfaces documentation.<br />

Assigning to Variables<br />

For best performance, keep the following suggestions in mind when assigning<br />

values to variables.<br />

Changing a Variable’s Data Type or Dimension<br />

Changing the data type or array shape of an existing variable slows <strong>MATLAB</strong><br />

down as it must take extra time to process this. When you need to store data<br />

of a different type, it is advisable to create a new variable.<br />

This code changes the type for X from double to char, which has a negative<br />

impact on performance:<br />

X = 23;<br />

.<br />

-- other code --<br />

.<br />

X = 'A';<br />

.<br />

-- other code --<br />

% X changed from type double to char<br />

11-9

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

Saved successfully!

Ooh no, something went wrong!