0
votes

Using MATLAB I want to check 2 vectors, for example:

A = [1 2 3 4 5 6 7 8 9 10] 
B = [10 9 8 7 6 11 12 13 14 15] 

and write a matrix that checks each element B if it is in A, if it is not in A, then append the element to A. So in the end I should have a new matrix H=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]. I want to check vector A from the end. This is the code I have right now:

A=[1 2 3 4 5 6 7 8 9 10]; 
B=[10 9 8 7 6 11 12 13 14 15]; 

for i=A(end:-1:1)
   for j=B(1:1:end)
      if B(j)==A(i)
         pass 
      else
         C=B(j); 
         H=[A,C];  % i want to append the new values at the end of vector A
      end 
    end 
end 

The error I get is in the if statement: if B(j)==A(i) Index exceeds number of array elements.

2

2 Answers

0
votes

Use ismember to find non-similar elements of B and concatenate them with A

H = [A B(~ismember(B,A))];
0
votes

Your error is that your loop variables i and j contain elements of A and B, not indices into them.

For example, these two loops produce the same output:

A = [5,2,1];
for i=A
   disp(i)
end
for i=1:numel(A)
   disp(A(i))
end

You should use for i=numel(A):-1:1, not for i=A(end:-1:1).


A slightly simpler alternative to the one-liner by Sardar is this:

H = unique([A,B]);

In this case, H is always sorted.