MATLAB: Calculation speed/time changes for same operation

big matrixcalculationchangesequationiterationMATLABmatrixmemorysolverspeed

Hi all. I have come across a very weird issue lately. I have a long piece of code setup where iteratively the same code snippets get called. There is this one moment in the code where a large equation/matrix solve has to be done:
U(freedof,:) = K(freedof, freedof)\F(freedof,:);
Where:
U = zeros(verylargenumber, 24);
F = (verylargenumber by 24);
K = (verylargenumber by verylargenumber);
The strange thing is, i.e. that when the first time this equation is solved it takes 130 seconds and every second time (even with different input variables) this equation keeps going. It seems that MATLAB can't do it again. If I do the equation with the same input from iteration 2 but then in iteration 1, it also takes 130 seconds.
Does anyone know what can cause this problem and what is a possible solution. Personally, I was thinking it had something to do with a memory issue…
Greetings
Daan

Best Answer

It definitely is a memory issue. Simplest is to get more memory, which is relatively cheap.
If the array is always the same size, you might be able to resolve the problem by not creating a new array each time on the fly. You are now forcing MATLAB to allocate a large chunk of memory. So, if instead, you just stuff the new array into the old one, like this
A(:) = K(freedof, freedof);
U(freedof,:) = A\F(freedof,:);
you might be able to avoid that allocation step. Again, it requires a fixed size array.