MATLAB: 2 Loops of same size, 1 goes very quick but one is very slow.

for loopMATLABmatrixmatrix arrayslow

Hello,
I have 2 loops with 4 index each. Every loop is of this form
X1 =zeros (10,11);
s= zeros(1,10^2*11^2);
for i = 1:10
for j = 1:10
for k = 1:11
for l = 1:11
counter = counter + 1
s(counter) = 2;
X1(i,k) = X1(i,k) - 1;
X1(j,l) = X1(j,l) - 1;
X = reshape(X1',1,[]);
T1 = {s,X} ;
V1 = horzcat(T1{:}) ;
A(counter,:) = V1(:);
X1 =zeros(10,11);
s= zeros(1,10^2*11^2);
end
end
end
end
The first loop does what it should do very quickly. And the second one is exactly of the same form but this runs very slowly.
I watch the variable "counter" to see how fast it runs and the first loop is finished after a few seconds, but the second one needs already 2 minutes for the first 500 cycles.
Why is it so slow and what can I do to make it faster ?
Best regards !

Best Answer

Here is a simple way to create your A (the one with +1 and +2)
[v1, v2] = ndgrid(num2cell(eye(110), 2)); %110 is 10*11
vsum = cellfun(@plus, v1, v2, 'UniformOutput', false);
vsum = cell2mat(vsum(:));
Apos = [2*eye(size(vsum, 1)), vsum];
Your A with -1 and -2 is simply:
Aneg = [2*eye(size(vsum, 1)), -vsum];
Note that the order of the rows is going to be different from what your loops generate but I assume it doesn't matter.