In general, you speed up Matlab programs by computing whole vectors or matrices at once, rather than writing loops. In this case, you can generate a "logical" vector that contains 1
in each column where the corresponding column in A has different values in rows 4 and 5, and 0
in the other columns:
selected_columns = A(4, :) ~= A(5, :);
Then you want to collect all the rows of A, in the columns where the two rows are different:
B = A(:, selected_columns);
I tested the idea in Octave, since I don't actually have Matlab:
octave-3.4.0:7> A = [1, 1, 2, 2, 3, 4, 5;1, 2, 3, 2, 1, 4, 5]
A =
1 1 2 2 3 4 5
1 2 3 2 1 4 5
octave-3.4.0:8> selected_columns = A(1, :) ~= A(2, :)
selected_columns =
0 1 1 0 1 0 0
octave-3.4.0:9> B = A(:, selected_columns)
B =
1 2 3
2 3 1
This isn't exactly equivalent to your original code, but it's probably closer to what you meant anyway. Specifically, if A has more than 4000 columns, my code will include the extra ones, while yours will drop them. My code also doesn't care about the initial value of B, while yours can include extra columns from B that weren't in A. Similarly, your code can fail if A is narrower than 4000 columns, or if B is too narrow to hold all the unequal columns from A.