Pages

Search This Blog

Tuesday, March 1, 2011

Code Optimization in MATLAB

During the undergraduate studies, whenever a student is given a programming problem to write code for it, the most important thing for him is to write a piece of code that gives the desired output. Most of the time, he never bothers to think how much time the code takes to give the desired output. This approach can work well as long as you are a student, but professionals think differently. They write a code that produces the desired result in the least possible time and using minimum possible resources. And for that matter, they have to optimize their code.

Usually, for a given programming problem, there may exist a number of solutions that output the required result. But the best of them is the one that is the shortest and the fastest. So, have you ever thought how much time your piece of code takes for execution?

In MATLAB, there is a simple command to find out the time taken by a code for execution: tic, toc. Write the code between tic and toc and run it. After the execution completes, MATLAB will tell the amount of time the code took to run.

tic;
% here goes the code, for example:
membrane;
toc;

% Output: Elapsed time is 0.150652 seconds.

Whenever you write a code, try to minimize this elapsed time and eventually you will get to the optimum code.

No comments:

Post a Comment