Info
This question is closed. Reopen it to edit or answer.
How do I avoid using for loop when I want to treat the rows of a matrix individually?
1 view (last 30 days)
Show older comments
For each row of 2-column matrix A, for example
a1=[1 2],
I would like to do the following:
1) Find all rows of 4-column matrix B that have a1 as their first two columns, then use their last two columns to form a new 2-column matrix C1. Say
B=[1 2 1 3;
1 2 1 4;
1 3 1 4;
1 2 1 6;
1 4 1 5;
1 5 1 3;
1 5 1 7]
, hence the 1st, 2nd and 4th rows satisfy the condition so C1=[1 3;1 4;1 6].
2) Check if all rows of C1 are included in another 2-column matrix D. If so, then return 1 for a1, otherwise return 0. For example, if
D=[1 3;
1 4;
1 5;
1 6],
then it returns 1 for a; for another
a2=[1 5],
C2=[1 3;1 7], as [1 7] is not included in D, it returns 0 for a2.
So if
A=[1 2;1 5] then the result is [1;0].
Now I am using a for loop to do what I want. I would like to improve the efficiency of my program. Is there a way of doing so without using a for loop?
result=zeros(size(A,1),1);
for i=1:size(A,1)
C=B(B(:,1)==A(i,1)&B(:,2)==A(i,2),[3,4]);
if(all(ismember(C,D,'rows')))
result(i,1)=1;
end
end
0 Comments
Answers (2)
Andrei Bobrov
on 3 Mar 2016
Edited: Andrei Bobrov
on 3 Mar 2016
B=[1 2 1 3;1 2 1 4;1 3 1 4;1 2 1 6;1 4 1 5;1 5 1 3;1 5 1 7];
A=[1 2;1 5];
D=[1 3;1 4;1 5;1 6];
[lo,ii] = ismember(B(:,1:2),A,'rows');
io = ii(lo);
[C,b] = unique(B(lo,3:4),'rows');
io = io(b);
iou = unique(io);
[lo0,i1] = ismember(D,C,'rows');
result = histc(io(i1(lo0)),iou) >= histc(io,iou);
or
result = ones(size(A,1),1);
[lo,ii] = ismember(B(:,1:2),A,'rows');
y = ii(lo).*~ismember(B(lo,3:4),D,'rows');
result(unique(y(y~=0))) = 0;
0 Comments
Jos (10584)
on 3 Mar 2016
This will work for unique rows of A:
B=[1 2 1 3;1 2 1 4;1 3 1 4;1 2 1 6;1 4 1 5;1 5 1 3;1 5 1 7];
A=[1 2;1 5];
D=[1 3;1 4;1 5;1 6];
[~, LOC] = ismember(B(:,[1 2]), A, 'rows')
Result = arrayfun(@(k) any(LOC==k) && all(ismember(B(LOC==k,[3 4]),D,'rows')),1:size(A,1))
0 Comments
This question is closed.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!