# Vectorize - C->Matlab / Heat equation

1. Feb 13, 2006

### Koubaros

Vectorize - C-->Matlab / Heat equation

I want to 'translate' some programs I had in C for matlab but by sigtly optimizing the code for matlab use. I am new in matlab. So, I had the following code:

(1) for K = 1:dT:M

(2) for I = 1:N+1
dU(I) = (U(I+1)-2*U(I)+U(I-1))/dX^2;
end

(3) for I = 1:N+1
U(I) = U(I)+dU(I)*dT
end

end

This actually is a simple implementation of an explicit scheme for the numerical solution of the heat equation. Now I managed to do this and eliminate the (2) and (3) loop:

(1) for K = 1:dT:M

(2) dU(1:N+1) = (U([2:end 1])-2*U+U([end 1:end-1]))/dX^2;
U(I+1)-->U([2:end 1])
U(I-1)-->U([end 1:end-1])

(3) U(1:N+1) = U(1:N+1)+dU(1:N+1)*dT

end

I could really use your help in order to eliminate the (1) time loop, in a way that the values of U(1:N+1) are stored for each time step dT or, in case M is very large this would take a lot of memory and time, get 'snapshots' every a couple of timesteps which I could define explicitly.