Reputation: 935
I have a matrix D as follows:
D=[
1 2
3 4
5 6
]
What I want to do is to test if my coordinate at position (ii,jj)
belongs to a one line in D.
In other terms, I have a for loop, and inside it, I want to increase a variable by 1 if the condition that verifies "(ii & jj) belongs to a line of D" is true.
For example, we can do this manually:
var = 0;
for ii = 1: 20
for jj = 1:30
if((ii==1 && jj==2) || (ii==3 && jj==4) || (ii==5 && jj==6))
var = var + 1;
end
end
end
This is straightforward since the matrix D contains only 3
lines. But in my work, I have of about 1000
lines, so D is of size 1000*2
. In this case, I have to find a method which can do the same job as I have written above but automatically and in a very fast manner. But how?
In fact one can think to use ismember
, for example:
var = 0;
for ii = 1 : 20
for jj = 1 : 30
if(ismember(ii, D(:,1)) && ismember(jj, D(:,2)))
var = var + 1;
end
end
end
But this is not correct, since for example, the code just above can find ii=1
and jj=6
, but in this case (ii,jj)
will be (1,6)
and which does not belong to any of (1,2)
, (3,4)
and (5,6)
.
Please, any help will be very appreciated!
Upvotes: 0
Views: 100
Reputation: 65430
You can use the 'rows'
input to ismember
to check if your array is a row within the matrix
tf = ismember([ii,jj], D, 'rows');
You can also check multiple values of ii
and jj
at once
% Create all permutations of ii and jj
[ii,jj] = ndgrid(1:20, 1:30);
% Test all of these permutations to see which ones are in D
tf = ismember([ii(:), jj(:)], D, 'rows');
And then to compute var
var = sum(tf);
If you are dealing with non-integers, you should use ismembertol
instead to deal with possible floating point errors.
Upvotes: 3