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.