user4326614
user4326614

Reputation: 61

compare a cell in a matrix with all the cells in another and store the result in a third matrix

I want to compare all the cells coordinates in matrix X, such that each cell is compared to all the coordinates in another matrix called Yint (Yint contains two columns and 65 rows each of which represents the coordinates (x,y) for a cell).

If the coordinates of a cell in X is equal to any of the coordinates in Yint then store 1 else 0 in a third matrix that is called labels.

Row 33 in Yint is just a flag in Yint matrix that's why I neglected it.

The problem is that the labels matrix always gives me zeros. I think there is something wrong in my code. Knowing that there are values in X that should satisfy the condition and store 1 at the labels matrix.

labels = zeros(65536, 1); 

Yint= round (Y);

counter=1;

for row = 1:1:rows
    for col = 1:1:cols
        pointer=1;
        for pointer=1:1:65
               if (isequal(row , Yint(pointer,1)) && isequal(col , Yint(pointer,2)) && pointer ~= 33)   
                   labels(counter) = 1;     
               else
                   labels(counter) = 0;
               end
         end
        counter=counter+1;
    end   
end

Matrices rows X columns:

Yint: 65 X 2

X: 256 X 256

labels: 65536 X 1

A reduced example:

X = [3  5  3;              
     2  7  4;                     
     1  7  2]                     

Yint = [1 1;
        2 3;
        3 3]

labels matrix can be viewed as:

labels = [1 0 0;              
          0 0 1;                     
          0 0 1]                     

However, we want it to be a vector (9x1) and what we get is:

labels = [1;
          0;
          0;
          0;
          0;
          1;
          0;
          0;
          1]

Upvotes: 2

Views: 103

Answers (1)

Santhan Salai
Santhan Salai

Reputation: 3898

For your given example and expected results, this should work:

Yind = sub2ind(size(X),Yint(:,1),Yint(:,2));
out = zeros(size(X));
out(Yind) = 1;
out = reshape(out.',1,[]).';

Results:

Input:

X = [3  5  3;              
     2  7  4;                     
     1  7  2];

Yint = [1 1;
        2 3;
        3 3];

Output:

out =

 1
 0
 0
 0
 0
 1
 0
 0
 1  

Additional work if you want to match all the occurrences instead of positions

Yind = sub2ind(size(X),Yint(:,1),Yint(:,2));

out = arrayfun(@(x) any(x == X(Yind)),X);

Your output(for the same input) will be something like this:

>> out

out =

 1     0     1
 1     0     1
 0     0     1

You could reshape this as you want:

out = reshape(out.',1,[]).';

After reshaping:

>> out

out =

 1
 0
 1
 1
 0
 1
 0
 0
 1

Upvotes: 2

Related Questions