How can I do setdiff() between 2 arrays row by row without a loop?

I'm trying to do the difference between 2 arrays with setdiff function but I don't get the expected result.
A = [15 8 5 9 10 14 17 7 20 12 6 16 2 4 11 13 3 1 19 18
10 19 13 15 1 16 6 14 17 8 11 18 20 5 2 12 7 9 4 3
15 8 5 9 10 14 17 7 20 12 6 16 2 4 11 13 3 1 19 18
13 12 3 14 4 19 2 16 10 18 20 6 15 5 7 17 1 9 11 8
13 12 3 14 4 19 2 16 10 18 20 6 15 5 7 17 1 9 11 8];
B = [16 19 15 5 8 1 3 20 14 18
4 14 13 2 20 9 15 7 6 12
14 2 12 13 4 8 5 19 18 20
3 10 19 13 15 1 16 6 14 17
12 11 6 10 13 7 16 19 15 5];
When I execute the instruction I get:
setdiff(A,B)
ans =
0×1 empty double column vector
But I would like to get:
out =[ 9 10 17 7 12 6 2 4 11 13
10 19 1 16 17 8 11 18 5 3
15 9 10 17 7 6 16 11 3 1
12 4 2 18 20 5 7 9 11 8
3 14 4 2 18 20 17 1 9 8];
Is there some way to get it without a loop?

 Respuesta aceptada

While your result shows that out is a 5x10 array, it is not guaranted in a generic case, because if you do setdiff() row by row on A and B, the number of elements will not always be the same row by row.
Why so obsessed with "no for-loop"? For-loop could be simple, faster and easy to understand. I can think of one way to do your task without for-loop, but do you think it is easy to follow?
ca=mat2cell(A,repmat(1,1,size(A,1)),size(A,2))
cb=mat2cell(B,repmat(1,1,size(B,1)),size(B,2))
out=cell2mat(cellfun(@(a,b) setdiff(a,b),ca,cb,'uniformoutput',false))

1 comentario

Thank you for your answer. I'm trying to learn how to execute actions in Matlab in different ways.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Productos

Versión

R2018b

Preguntada:

el 21 de Feb. de 2019

Comentada:

el 21 de Feb. de 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by