input matrix A with added columns which are the columns of $eye(size(A)(1))$ that do not appear in $A$

16 Views Asked by At

I want to make Matlab returns the input matrix A with added columns which are the columns of $eye(size(A)(1))$ that do not appear in $A$.

Example:

input$$A = \begin{matrix}2 & 0 & 1 & 3 \\ 4 & 1 & 2 & 7 \\ 2 & 0 & 5 & 6\end{matrix}$$

output $$A = \begin{matrix}2 & 0 & 1 & 3 & 1 & 0 \\ 4 & 1 & 2 & 7 & 0 & 0 \\ 2 & 0 & 5 & 6 & 0 & 1\end{matrix}$$

I tried to put

A = input('Matriz A: ')

I = eye(size(A)(1))
m_ = (intersect(I',A','rows'))'
m_(size(I)(1),size(I)(1)) = 0
for i = 1:size(I)(1)
  p = 0
  for j = 1:size(I)(1)
    if I(:,i) != m_(:,j)
      p = p + 1
    end
    if j = size(I) && p == size(I)(1)
      A(:,size(A)(2) + y) = I(:,i)
    end
  end
end

But there is something going wrong. What are the modifications I have to do to this works?

1

There are 1 best solutions below

0
On BEST ANSWER

There is some erros on your code. Notice size(I)(1) produces an error and you probably mean size(I,1). Also, the logical comparison != produces an error. The "not equal to" in MATLAB should be ~=. You also don't need the for loops, as you can accomplish what you are trying with MATLAB builtin functions intersect and setdiff.

Doing it step by step, you can use the code:

A = [2 0 1 3
    4 1 2 7
    2 0 5 6];
I = eye(size(A,1));

inter=intersect(I',A','rows')'; % get the columns in I that are in A
A = [A setdiff(I',i','rows')'] % concatenates A and the columns in A not in A

To get:

A =

     2     0     1     3     0     1
     4     1     2     7     0     0
     2     0     5     6     1     0