# Speeding up loop-rich Matlab function to calculate temperature distribution

I would like to speed up this function as much as possible in Matlab. This is part of a bigger simulation project, and as it is one of the most called functions within the simulation, this is crucial.

For now, I tried generating a MEX file, but the speed was not better.

Vectorizing seems difficult (but would be beneficial due to the nested loops), given the non-linear operations.

What I'm trying to compute with this is the degree of temperature mixing between water layers, given by these equations:

\begin{align} T_j =&\ r\ T_{j+1} + (1-r)\ T_j\quad&\textrm{for } j \in [i,\ i+\Delta i]\\ T_{j+1} =&\ (1-r)\ T_{j+1} + r\ T_j \end{align}

and $n$ is the total number of water layers. This must be calculated for all $j$, this is for all the layers, at all timesteps.

function y = mixing(T,dis,rr,n)
%% ===================================================================
%  input: temperature of cells array T, distance array dis, number of cells
%         n, mixing ratio r
%
%  output:  new temperature array
%
%  purpose: calculates the temperature array of next timestep
%  ===================================================================

for j = 1:n
i = 1;
r = rr;
while i < dis(j)+1 && j+i <= n
if (dis(j) < i)
r = r*(dis(j)-floor(dis(j)));
end
d = T(j+i-1);
T(j+i-1) = r*T(j+i) + (1-r)*T(j+i-1);
T(j+i) = r*d + (1-r)*T(j+i);
i = i + 1;
end
end

y = T;
end


Inputs: T is a 10 × 1 double, dis is a 10 × 1 double, rr is a 1 × 1 double, and n is a 1 × 1 integer value.

• I'm not quite sure your equations are correct, as for me they simply resolve to $T_j = T_{j+1}$... – knedlsepp Dec 15 '14 at 10:29
• You can use the hints given in my answer here: codereview.stackexchange.com/a/77553/43192 – Lukas Jan 14 '15 at 22:42
• I'll not be able to review the code, but for clarity: I couldn't understand the "n" that is the total number of water layers, it's not in the equations? – Gürkan Çetin Jul 15 '15 at 20:24