1
votes

I am trying to compare two vectors of different size. For instance when I run the code below:

A = [1 4 3 7 9];
B = [1 2 3 4 5 6 7 8 9];

myPadded = [A zeros(1,4)];

C = ismember(myPadded,B)

I get the following output:

C = 1 1 1 1 1 0 0 0 0

However, I want an output that will reflect the positions of the compared values, hence, I would like an output that is displayed as follows:

C = 1 0 1 1 0 0 1 0 1

Please, I need some help :)

3

3 Answers

6
votes

There are 2 points. First, you are writing the inputs of ismember in the wrong order. Additionally, you do not need to grow your matrix. Simply try ismember(B, A) and you will get what you expect.

5
votes

The function ismember(myPadded, B) returns a vector the same size of myPadded, indicating if the i-th element of myPadded is present in B.

To get what you want, just invert parameter order: ismember(B, myPadded).

0
votes

A quick way of doing this is to use logical indexing. This will only work if the last digit of B is included in A.

A = [1 4 3 7 9];
c(A) = 1; % or true.

An assumption here is that you want to subindex a vector 1:N, so that B always is B = 1:N. In case the last digit is not one this is easy to fix. Just remember to return all to its previous state after you are done. It will be 2 rows extra though.

This solution is meant as a special case working on a very common problem.