I have a very big Matlab simulation project in my hands, which I wanted to optimize, since I'm running it many times to tune parameters and the like.
Using Matlab's profile
I identified one function that is eating up most of my time, specifically the output(i,1)
assignment line.
This function is called a LOT, where input
is a 10x1
double passed as an argument, and output
is also a 10x1
vector.
function output = my_function(input)
a = size(input,1);
output = input*0;
dens = density(input);
% for each i, output(i) is the maximum between output(i+1) and mean(output(i+1:end))
for i = 1:a-1
output(i,1)= max(mean(dens(i+1:a,1)),dens(i+1,1));
end
output(a,1) = dens(a,1);
end
density()
function:
function dens = density(input)
dens = 1000*(1 - (input+288.9414)./(508929.2.*(input+68.12963)).*(input-3.9863).^2);
end
My ideas:
- I think vectorization would maybe help to get rid of the loop, but I'm not familiar at all with the technique.
- Is there a faster/alternative way to calculate the
mean
(maybe without Matlab's built-in function call?)
density
function defined? It isn't defined in the standard MatLab functions – syb0rg Dec 5 '14 at 18:15density
is an external function I declared. It is not relevant for my question, asdens
is also a10x1
double vector – titus.andronicus Dec 5 '14 at 18:16output(i,1)= max(mean(dens(i+1:a,1)),dens(i+1,1));
, thus the vectorization I mentioned – titus.andronicus Dec 5 '14 at 18:31density
does matters because you might be able to calculateoutput(i,1)
from values inoutput
rather than taking a mean of values indens
. My offhand thought is that you are iterating in the wrong direction. Given what you are doing, you should iterate down not up and calculate the mean as you go. Someone like syb0rg with more knowledge of Matlab could probably give you better help if you offered a working example with all code. – Brythan Dec 5 '14 at 21:17density
function in the last edit – titus.andronicus Dec 5 '14 at 22:14