Relation of Elements of matrix

1 回表示 (過去 30 日間)
ANAND ASP
ANAND ASP 2021 年 1 月 29 日
コメント済み: Walter Roberson 2021 年 1 月 29 日
A = [1 2
2 6
2 3
2 7
3 4
5 4
6 3
4 7]
i have matrix A,
if i select B=2, i want output as 1 2 3 6 7, it shows relatiionship of 2
if i select B=3, i want output as 2 3 4 6, it shows relatiionship of 3
  1 件のコメント
KSSV
KSSV 2021 年 1 月 29 日
What do you mean by relationship of 2? What is B?

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

採用された回答

Walter Roberson
Walter Roberson 2021 年 1 月 29 日
編集済み: Walter Roberson 2021 年 1 月 29 日
A = [1 2
2 6
2 3
2 7
3 4
5 4
6 3
4 7]
A = 8×2
1 2 2 6 2 3 2 7 3 4 5 4 6 3 4 7
B = 2
B = 2
unique([B; A(A(:,1) == B,2); A(A(:,2) == B,1)]).'
ans = 1×5
1 2 3 6 7
However, the basis for including the number itself is not clear. If B does not occur at all in A, then I would argue it would be more appropriate for the result to be empty than for it to include B itself.
  6 件のコメント
Paul Hoffrichter
Paul Hoffrichter 2021 年 1 月 29 日
編集済み: Paul Hoffrichter 2021 年 1 月 29 日
After adding a note that removing the sort was faster, I then started thinking that the two line solution might actually be faster than the more one-line solution. (Usually, I think of one-line solutions as not only more elegant, but also, usually also faster.)
Yet, the two line solution was 4-5 times faster than the one line solution. Not that it matters much since the time for either one is negligible.
B = 12345;
n = 1e8;
A = randi(n/2000,n,2);
tic
z1 = unique([B; A(A(:,1) == B,2); A(A(:,2) == B,1)]).';
toc
tic
[r, ~] = ind2sub( size(A), find(A==B) );
z2 = unique( A( r ,: ) )';
toc
Elapsed time is 0.665452 seconds.
Elapsed time is 0.154779 seconds.
Walter Roberson
Walter Roberson 2021 年 1 月 29 日
B = 12345;
n = 5e7;
A = randi(n/2000,n,2);
tic
z1 = unique([B; A(A(:,1) == B,2); A(A(:,2) == B,1)]).';
toc
Elapsed time is 0.759719 seconds.
tic
[r, ~] = ind2sub( size(A), find(A==B) );
z2 = unique( A( r ,: ) )';
toc
Elapsed time is 0.251981 seconds.
tic
z3 = unique(A(any(A == B,2),:)).';
toc
Elapsed time is 0.306312 seconds.

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

その他の回答 (1 件)

Paul Hoffrichter
Paul Hoffrichter 2021 年 1 月 29 日
B = 3;
[r, ~] = ind2sub( size(A), find(A==B) );
z = A(sort(r),:);
zu = unique(z(:))'
  2 件のコメント
Paul Hoffrichter
Paul Hoffrichter 2021 年 1 月 29 日
B = 2;
[r, ~] = ind2sub( size(A), find(A==B) );
z = unique( A( sort(r) ,: ) )'
Paul Hoffrichter
Paul Hoffrichter 2021 年 1 月 29 日
Don't need the sort, so this is faster:
[r, ~] = ind2sub( size(A), find(A==B) );
z = unique( A( r ,: ) )'

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

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by