MATLAB: There is any function substituting for this ‘for loops’

for loop

for n = 1:99;
for a=1:size(A{n},1);
for m = n+1:100;
for b = 1:size(A{m},1);
if A{n}(a,:) == A{m}(b,:) ;
A{m}(b,:) = zeros(x,1);
% x = size(A{m},2)
end
end
end
end
end
A{n} has each different not only contents of cell but also size of cell. My meaning of this codes is willing to compare all columns of nth cell A with all columns of mth cell A.(n<m) If two columns are same,the column of mth cell will change into zeros.
for example,
A{1}=[1 0 1 1;1 1 1 1;0 0 1 0;]
A{2}=[1 1 0 0;1 1 0 1;0 0 1 0;]
A{3}=[1 1 1 1;0 0 1 1;1 0 1 1;]
The upper code makes them like this.
A{1}=[1 0 1 1;1 1 1 1;0 0 1 0;]
A{2}=[1 1 0 0;1 1 0 1;0 0 0 0;]
A{3}=[0 0 0 0;0 0 1 1;0 0 0 0;]
This code has no problem working, but it takes too long times. so, anybody knows a way to make this code more simply and quickly? frankly speaking, I don't want to use 'for' loops…hmm. I don't know it's possible..
I need your help.
PS. Each cell has a matrix, and its size is about 1000000X10. A size of A{n} continuously changes, but it is at least 50X1. In addition, a sameness of columns comes to 80%

Best Answer

  • Just some simplification for your loop methods:
    for n = 1:99
    An = A{n}; % avoid repeated indexing
    for a = 1:size(An, 1)
    An_a = An(a, :);
    for m = n+1:100
    Am = A{m};
    for b = 1:size(Am, 1)
    if all(An_a == Am(b, :))
    Am(b, :) = 0; % scalar expansion! zeros(x,1);
    end
    end
    A{m} = Am;
    end
    end
    end
    Perhaps "if all(An_a == Am(b, :))" can be accelerated as:
    if any(An_a - Am(b, :)) == 0