MATLAB: Small Matrix (30×1) using significant time/memory to update in a loop

matrix calculationmemory usagespeed

I have a small vector Rv (30×1) which need to be updated in every loop. Before going in the loop, I have initiated the vector assigning values zeros. On profiling (with memory and time), I find that this updating step takes a significant amount of time compared to others. Also, the memory usage seems to be higher than for what a 30×1 matrix should use. I am attaching the image of profiler analysis. All the other variables appearing (like Kd K_Ir_Ac etc) are simple scaler variables.
What am I missing? What can I do the reduce the overhead in terms of memory and time usage?
This analysis was done for only a fraction of total time to test the complete function. On running the code upto final point (~100-200 times more loops that in this test run), these times will matter. And moreover, this is just out of curiosity as well!!

Best Answer

Preallocating this vector with zeros is a waste of time! At least it is if immediately after that, you replace the entire vector with other numbers. So don't waste that time. (In general, preallocation is a VERY smart thing to do.)
Next, how many times must MATLAB compute the product (Nav*V), and then divide by it? Why force a computation to be done repeatedly? In fact, you go further than that, since you form things like Ir/(Nav*V) multiple times.
Next, I'd not be at all surprised to find that there is a difference in time between
Rv = zeros(30,1);
Rv(:,1) = [stuff];
and
Rv = [stuff];
Next, are ALL of these scalar variables changing all of the time? I would sincerely bet they are not. So why not precompute some parts of this vector and save the results?
Finally, I was going to try optimizing how your line is written, but since it is an image, I cannot copy it into the MATLAB editor.
Related Question