Mac.
Mac.

Reputation: 303

get a matrix at the end of the loop

How I can get all C in a matrix at the end of the loop?

for i=1:size(A,1)
   for j=1:size(B,1)
       if B(j,3)==A(i,3)
       C=B(j,3);
       end
   end
end

Upvotes: 1

Views: 52

Answers (1)

Wolfie
Wolfie

Reputation: 30047

To collect all C which match your criteria, you could append them to a matrix:

C = [];
for i=1:size(A,1)
    for j=1:size(B,1)
        if B(j,3)==A(i,3)
            C = [C, B(j,3)];
        end
    end
 end

But if I understand, you want a matrix C containing all elements of B(:,3) which are also in A(:,3)?

You can simply do

C = B(ismember(B(:,3), A(:,3)), 3);

For example,

X = [5 9 8];
Y = [1 2 3 4 5 6 7 8];
X(ismember(X,Y))

% ans =
%    [5 8]

Upvotes: 1

Related Questions