3
$\begingroup$

I encountered a problem which seems very weird to me. I hope it can be understood from my description and is reproducible.

I try to add up elements of a matrice to a vector (part of FEM), an example would be this:

dirivekb[mat_, vek_, dirilist_, diriwerte_] := 
Module[{nnodes, maxdiri, vektorb},
vektorb = vek;
nnodes = Length[mat];
maxdiri = Length[dirilist];
For[i = 1, i <= nnodes, i++,
vektorb[[i]] = 
vektorb[[i]] - 
Sum[diriwerte[[j]]*mat[[i, dirilist[[j]]]], {j, 1, maxdiri}];
(*Print[vektorb[[i]]];*) 
];
Return[vektorb];
];

f[len_]:=(
lend=len/10.;
mat=Table[RandomReal[1],len,len];
vek=Table[RandomReal[1],len];
dirilist=Range[lend];
diriwerte=Table[RandomReal[1],lend];
AbsoluteTiming@(dirivekb[mat,vek,dirilist,diriwerte];)
)

f[2499.]

If I want to do this with a matrice of size 2499 time needed is 0.87 seconds. However, for a matrice of size 2500, the time consumption is huge. For that size, it would take an hour or so, since it then takes about one second per iteration in dirivekb, It seems the problem is the length of the dirilist. If I were to set

lend = len/20.;

then the threshold of the time increase would become 5000 elements. I infer that the problem occurs when more than 249 elements is operated on.

What is the reason for that and how can I fix it?

After all it's just elements being multiplied and added up. I tried to code it with Table and Total, since I thought the Sum would use a different method (although I wouldnt understand why) after a certain amount but the behaviour is the same.

$\endgroup$
6
$\begingroup$

You are using explicit nested loops so your problem in growing exponentially. See if you get enough advantage from vectorizing:

dirivekb[mat_, vek_, dirilist_, diriwerte_] := 
 vek - mat[[All, dirilist]].diriwerte
|improve this answer|||||
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.