First, forgive me for abusing the Matlab syntax to express mathematical material.
Consider the following code, where we do the same as in your example. Note that A,B,C are strings of X
X = zeros(3,N+1); X(:,1) = [2,5,3]; M= [1,0,2;3,1,0;1,1,0]; for i=1:N X(:,i+1) = M*X(:,i); end
This is just a matrix vector designation of the above code. I think this is even slower. Note that we could also calculate: X(:,i+1) = M^i * X(:,1) , which is even slower.
Please note that we can use eigenvalue decomposition:
[V,D] = eigs(M); X(:,i+1) = [V*D*inv(V)]^i * X;
therefore
X(:,i+1) = V*D^i*inv(V) * X;
So V*D^i*inv(V) is an explicit formula for the i+1 1th term of X I suggest calculating them analytically and reconnecting the formula that you enter into your code.
EDIT: I wrote code that should be close to the analytical solution of the system, you can compare the runtime. It seems that ultimately preallocation with your first method is still the fastest if you need ALL TERMS. If you need only one of them, my proposed method will certainly be faster.
clear;clc N = 10000000; tic A(1)= 2; B(1)= 5; C(1)= 3; A = zeros(1,N+1); B=A;C=A; for i=1:N A(i+1) = A(i) + C(i)*2; B(i+1) = B(i) + A(i)*3; C(i+1) = A(i) + B(i); end toc tic X = zeros(3,N+1); X(:,1) = [2,5,3]; M= [1,0,2;3,1,0;1,1,0]; for i=1:N X(:,i+1) = M*X(:,i); end toc tic M= [1,0,2;3,1,0;1,1,0]; [V,D]=eig(M); v=0:N; d=diag(D); B=bsxfun(@power,repmat(d,1,N+1),v); Y=bsxfun(@times,V * B, V \[2;5;3]); toc tic M= [1,0,2;3,1,0;1,1,0]; [V,D]=eig(M); v=0:N; d=diag(D); Y = ones(3,N+1); for i=1:N Y(:,i+1) = d.*Y(:,i); end Y=bsxfun(@times,V * B, V \[2;5;3]); toc