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

6 ビュー (過去 30 日間)
Izan Segarra
Izan Segarra 2019 年 2 月 21 日
コメント済み: Izan Segarra 2019 年 2 月 21 日
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?

採用された回答

Fangjun Jiang
Fangjun Jiang 2019 年 2 月 21 日
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 件のコメント
Izan Segarra
Izan Segarra 2019 年 2 月 21 日
Thank you for your answer. I'm trying to learn how to execute actions in Matlab in different ways.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by