# How can I optimize that loop?

I need to populate a matrix $$A_{kl}$$, where

$$k = (m-1)J+n$$ $$l = (p-1)J+q$$

And

$$m,p = 1, 2, ..., I$$ $$n,q = 1, 2, ..., J$$

Its components are (mnpq). For populate it, I'm using a expensive 4 Do loop

Do[
Do[
Do[
Do[
Print[m, n, p, q];
k = (m - 1) nC + n;
l = (p - 1) nC + q;
If[k <= l, A[[k, l]] = cf[Nfunc, xi, yi, wix, wiy, m, n, p, q],
0];
, {q, 1, J, 1}]
, {p, 1, I, 1}]
, {n, 1, J, 1}]
, {m, 1, I, 1}]


Knowing that $$A_{kl}$$ for a $$I=J=2$$, its components are (mnpq)

$$\begin{bmatrix} (1111) & (1112) & (1121) & (1122)\\ & (1212) & (1221) & (1222)\\ symm. & & (2121) & (2122)\\ & & & (2222)\\ \end{bmatrix}$$

Does anyone know a more efficient way to populate it?

• You don't say what the problem is. – Wolfgang Bangerth May 5 '20 at 18:39
• @WolfgangBangerth, the problem is that for $I\times J$ big, the 4 Do loop is very expensive. – Professor P. Cosmo Klunk May 5 '20 at 18:44
• Right, but you do have to fill every entry of the matrix and you have to call cf for each one of them. There isn't very much you can do about it -- if $I \times J$ is large, then necessarily it is expensive to fill that matrix. It's not like you're doing redundant work as far as I can see -- though of course I have no idea what cf actually does. – Wolfgang Bangerth May 5 '20 at 21:31
• @WolfgangBangerth, this problem was solved using only one Do loop, look up here: mathematica.stackexchange.com/questions/221172/…. Anyway, thank you. – Professor P. Cosmo Klunk May 6 '20 at 11:29