Until yesterday, I've never used MATLAB (however I've done a fair amount of programming in languages like C/C++, java, etc.). I'm trying to assist someone with optimizing one of their modules that takes many hours to run. Using the profiler, I found that one loop was taking the lion's share of the processing time. I've just come across the "vectorization" feature that is supposed to help make loops unnecessary. When I employ it to remove the offending loop (hopefully correctly), it cuts the processing time down by a whopping 87%! I just need someone to verify that I'm using vectorization correctly. Here is the code snippet from the module that I did the vectorization on:
for j = 1:20 f = f + nn(i,j) * log(p(j)); end
My attempt at vectorization:
j = 1:20 f = sum(nn(i,j) .* log(p(j)));
Am I using the correct multiplication operator in my code?
The module runs an iterative process. Normally there are 500 iterations and takes almost 9 hours on my dual quad-core i7-2600 @ 3.4GHz. When I set the number of iterations to 2 and then run the module with the two above variations, the profiler shows me the run time using the first algorithm is 679s compared to 88s using the second algorithm. That's huge! Question is, is the vectorization used correctly? (The final answers I'm getting are the same, but as I only have one data set, I can't say that the same result is not based on some characteristic of the data set I have.)