intersection of multiple arrays
古いコメントを表示
I have multiple 1D arrays with integers. Eg. A=[1,2,3,4] B=[1,4,5,6,7] C=[1,5,8,9,10,11]. Here 1 is repeated in all the arrays and 4 in A&B, 5 in B&C. I want these repeated values to be assigned to a single array, based on the size of the array, and removed from other arrays. How can I achieve this. Please help. TIA.
5 件のコメント
KSSV
2017 年 9 月 14 日
YOu want to remove 1, 5 and 4 from all the sets?
KL
2017 年 9 月 14 日
What do you mean by "based on the size of the array"?
Ananya Malik
2017 年 9 月 14 日
KL
2017 年 9 月 14 日
So you only wanto to remove 1 from all the matrices in the above example?
Ananya Malik
2017 年 9 月 14 日
編集済み: Ananya Malik
2017 年 9 月 14 日
採用された回答
その他の回答 (2 件)
KL
2017 年 9 月 14 日
A=[1,2,3,4];
B=[1,4,5,6,7];
C=[1,5,8,9,10,11];
M = {A,B,C};
N = {[B C], [A C], [A B]};
CommonElements = unique(cell2mat(cellfun(@intersect, M,N,'UniformOutput',false)));
NewM = cellfun(@(x) removeEl(x,CommonElements),M,'UniformOutput',false);
%and then
function x = removeEl(x,a)
for el=1:length(a)
x(x==a(el))=[];
end
end
Guillaume
2017 年 9 月 14 日
This is how I'd do it:
C = {[1 2 3 4], [1 4 5 6 7], [1 5 8 9 10 11]};
%sort cell array by increasing vector size:
[~, order] = sort(cellfun(@numel, C));
C = C(order);
%get all unique values
uvals = unique(cell2mat(C));
%go through all arrays, keeping all values in uvals, then removing them from uvals so they can't be used by the next array
for iarr = 1:numel(C)
C{iarr} = intersect(C{iarr}, uvals); %only keep the values in uvals
uvals = setdiff(uvals, C{iarr}); %and remove the one we've just used
end
celldisp(C)
1 件のコメント
Ananya Malik
2017 年 9 月 14 日
編集済み: Ananya Malik
2017 年 9 月 14 日
カテゴリ
ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!