The objective: Given an m by n matrix, I have written a function in Matlab that reorders the columns of the matrix to output linearly independent columns; other/redundant columns. Basically, it just pushes the redundant columns to the end of the matrix.
Here is my attempt at the code (which produces correct results):
function result = find_redundant_assets(A)
if (rank(A) == size(A, 2)) % if the rank is the same as the number of columns => full rank
result = A;
else % there exists at least one linearly dependent column
A_red = [];
for n = 1:(size(A,2)-1) % fix a column and compare to all neighbors to the right
for p = n+1:size(A,2) % loop through comparison columns
if ( isequal( A(:,p)' * round(A(:, n)'/ A(:,p)') == A(:,n)', ones(1, size(A,1)))) % TRUE iff the nth column is a scalar multiple of the pth column
A_red = [A_red, A(:,n), A(:,p)]; % add the linearly depedent rows
end
if (isequal(A(:,n)' * round(A(:, p)'/ A(:,n)') == A(:,p)', ones(1, size(A,1)))) % TRUE iff the pth column is a scalar multiple of the nth column
A_red = [A_red, A(:,p), A(:,n)]; % add the linearly depedent row
end
end
end
A_red = unique(A_red.', 'rows', 'stable')';
result = fliplr([A, A_red]);
result = unique(result.', 'rows', 'stable')';
result = fliplr(result);
end
end
This function gets pretty complicated, but it makes sense to me.
How can I improve my code? Does anyone know a better way to accomplish this task?
Also, I know this is not efficient code because I am constantly re-sizing the matrix.
A_red = unique(A_red.', 'rows', 'stable')'
contains the uninitializeA_red
on the left side ifrank(A) == size(A, 2)
. This will raise an error. \$\endgroup\$