User1772
User1772

Reputation: 91

How do I compare vector and matrix columns that satisfy a condition?

I have a 12x3 matrix:

point1 = [7.5   4   5
          8.5   4   5
         9.5    4   5
         10.5   4   5
         11.5   4   5
         7      4   5.5
         12     4   5.5
         6.5    4   6
        12.5    4   6
           6    4   6.5
          13    4   6.5
         5.5    4   7];

The following two vectors were obtained from point1 after certain procedure.

A1 = [7.5,4,5]; 
A8 = [6.5,4,6];

the row indices of A1 and A8 respectively in point1 are AIdx == 1 and AIdx == 8.

What I would want is to compare both of A1 and A8 to see which of them (or possibly both) has a non-integer at the same column as the 6th row of point1.

I have tried the following code:

AIdx = find(ismember(point1, vertcat(A1, A8), 'rows'));

    for ii = 1: numel(AIdx)

    % In case where a close point is found, compare if they are both in the same plane
    if isequal( mod(point1(AIdx(ii),:),1)~=0, mod(point1(6,:),1)~=0 )== true    
        point1(AIdx(ii),:) = [NaN,NaN,NaN];  %invalidate all AIdx in the same plane as point1

    elseif isequal( mod(point1(AIdx(ii),:),1)~=0, mod(point1(6,:),1)~=0 )== false   
        AIdx(ii,:) = [];
    end
end

However, I get the error message: “Index exceeds matrix dimensions.” and I have a feeling this is coming from the part

mod(Point1(AIdx(ii),:),1) 

whereby at ii = 2 (hence AIdx=8) there comes a problem.

Upvotes: 0

Views: 58

Answers (1)

Leander Moesinger
Leander Moesinger

Reputation: 2462

First about your error message:

In the first iteration you delete AIdx(1,:) in the elseif part. Therefore AIdx has afterwards only one element left, leading AIdx(2)to throw said error. What was the purpose of that part in the first place?

Now about your comparison:

It is only true if ALL non integers are at the same place. Unless I have greatly misunderstood the question, you wanted to check if even ONE non integer is at the same place.

for ii = 1: numel(AIdx)
    if any((mod(point1(AIdx(ii),:),1)~=0) & (mod(point1(6,:),1)~=0)) % check if ANY non integer is at the same place
        point1(AIdx(ii),:) = NaN;
    end
end

Also, here is a version without loop:

nonIntSix = repmat((mod(point1(6,:),1)~=0),2,1); % get indices of non integers in row six
NonIntA = mod(point1(AIdx,:),1)~=0; % same for A1 and A8
point1(AIdx(max(nonIntSix&NonIntA,[],2)),:) = NaN; % NaN all rows where at least one element the same

Or as single liner (faster):

point1(AIdx(max((mod(point1(AIdx,:),1)~=0) & (repmat((mod(point1(6,:),1)~=0),2,1)),[],2)),:) = NaN;

Upvotes: 1

Related Questions