From: Liqun on
u(x, y) is an unknown function, I need to compute u(x, y) at each time step t1 < t2 < t3 < ... < tk; The domain is discretized as x1 < x2 < x3 < ... < xm and y1 < y2 < y3 < ... < yn; I have the following code:

for t1 : tk
for x1 : xm
for y1 : yn
group 1;
group 2;
end
end
end

In group 1, I have to compute 300 parameters, which will be used in group 2. BUT all of the 300 parameters do NOT depend on time t. So, another option is to move group 1 out of the loop for time t. However, this will need 300 matrix of size m by n to store the 300 parameters at each grid points.

For the first method in the above code will repeat the computation for the 300 parameters many times, which will make the code inefficient.
For the other method, if m and n are very large, the 300 matrix will cost much memory too.

Would you please help me here? Which one will be better? or is there any other choice for this kind problem? Thank you very much!
From: Walter Roberson on
Liqun wrote:

> In group 1, I have to compute 300 parameters, which will be used in
> group 2. BUT all of the 300 parameters do NOT depend on time t. So,
> another option is to move group 1 out of the loop for time t. However,
> this will need 300 matrix of size m by n to store the 300 parameters at
> each grid points.
> For the first method in the above code will repeat the computation for
> the 300 parameters many times, which will make the code inefficient.
> For the other method, if m and n are very large, the 300 matrix will
> cost much memory too.


> Would you please help me here? Which one will be better? or is there any
> other choice for this kind problem? Thank you very much!

First thought: instead of 300 matrices, you could use a cell array, or
an m x n x 300 matrix. Easier to code.

Second thought: if you have the memory, you might as well use it for
efficiency. If you don't have enough memory, every parameter that you
can afford to pre-compute is time saved, so fill in as many of the slots
as you can afford the space for and compute the rest on the fly.

If m and n vary from run to run, you may not know at coding time how
much you can afford. In such a case, you could use a hybrid approach
with a cell array, that pre-computed as much as you had space for, and
then when you enter the loop and you need a parameter, you check whether
that parameter is available (~isempty(parms(K)) and if so use the stored
value and if not then compute it on the fly.