Tips for Writing Efficient Code

5 views (last 30 days)
Tarun
Tarun on 5 Feb 2015
Edited: Tarun on 5 Feb 2015
I'm looking for some specific insights for writing efficient code. In my problem, I have 4 non-linear equations and 4 dependent variables. I'm using Newton-Raphson method to find the zeros. Everything is technically working, but I'd like some insights into making this code more efficient.
1. The core of this method is evaluating dx = -J/F where F is a 4x1 array of numbers (calculated from the non-linear equations) and J is a 4x4 matrix of number (calculated from the partial derivatives of the non-linear equations). This one calculation takes up ~24% of my computational time. Is there a more efficient way to do this calculation?
2. My code iteratively finds the zeros (hence NR-method). Basically, I iteratively calculate the zeros until I achieve some arbitrary error tolerance (i.e. while (error>1e20) ... NR-method ... end). In timing various protions of my code I've discovered that execution of the while statement (not the code in the loop) accounts for 20% of my computation. This seem crazy to me. Here's my timing code (simplified).
inner_loop_time = 0
outer_loop_start = cputime;
while (check)
inner_loop_start = cputime;
%NR-METHOD
inner_loop_end = cputime;
inner_loop_time = inner_loop_time+inner_loop_end-inner_loop_start;
end
outer_loop_end = cputime;
outer_loop_time = outer_loop_end-outer_loop_start;
In this code, I would have expected inner_loop_time to be very close to outer_loop_time, but I find that (outer_loop_time-inner_loop_time)/outer_loop_time is about 0.2. Am I timing this incorrectly? Or is there a more efficient way to execute a while loop?
Thanks in advance!

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!