フィルターのクリア

How to create an array out of a matrix based on criteria.

3 ビュー (過去 30 日間)
DuckDuck
DuckDuck 2014 年 11 月 18 日
コメント済み: Thorsten 2014 年 11 月 19 日
Suppose i have a matrix of
a=[1,2;
1,3;
1,4;
2,12;
2,15;
5,7;
5,8;
6,98;
6.99;
7,8;
7,9;
7,11;
9,14;
9,16;
12,18;
14,20;
20,35;
98,102;
99,204;
204,300];
I want to create arrays arrays that will contain elements mentioned in the pair.
b=[1,2,3,4,12,15,18]
c=[5,7,8,9,14,16,20,35]
d=[6,98,99,102,204,300]
The idea is that if 2 is in a pair of 1, then every other element in pair with 2 will end up in the b array. So on and so forth for different categories, b,c,d,.... How can I achieve that kind of iteration in Matlab?

採用された回答

Thorsten
Thorsten 2014 年 11 月 18 日
編集済み: Thorsten 2014 年 11 月 18 日
b = a(1,:); c = [];
for i = 2:size(a, 1)
if ~isempty(intersect(a(i,:), b))
b = union(b, a(i,:));
else
c = union(c, a(i,:));
end
end
  2 件のコメント
DuckDuck
DuckDuck 2014 年 11 月 18 日
編集済み: DuckDuck 2014 年 11 月 18 日
Thanks Thorsten, but this solution does not generalise. What if i'll have more b, c, d, e?
Thorsten
Thorsten 2014 年 11 月 19 日
Oh, you changed the question. That's not fair! (Just kidding.) The generalized solution is
b{1} = a(1,:);
for i = 2:size(a, 1)
bi = 1;
while bi <= numel(b) && isempty(intersect(a(i,:), b{bi}))
bi = bi + 1;
end
if bi <= numel(b) % append a(i,:) to b{bi}
b{bi} = union(a(i,:), b{bi});
else % create bi'th entry in cell b
b{bi} = a(i, :);
end
end
for bi = 1:numel(b)
disp(b{bi})
end

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by