How to check for reversed pairings in columns of a matrix?
1 回表示 (過去 30 日間)
古いコメントを表示
I have a matrix representing arcs in a network, where the first two columns represent the the "to" and "from" nodes and the other eleven columns represent capacities for various products. In my current matrix, there may be both (1,2) and (2,1) in the first two columns, but only (3,5) and not (5,3), for example. What I need to do is to produce a larger matrix that includes both "flipped pairs" in the first two columns. So I would like to have both [1,2] in the first two columns, and [2,1], each with their own values in the remaining columns. But if [3,5] exists and [5,3] doesn't then I want to add a row to the matrix that goes [5,3] followed by the values in the rest of the row for the [3,5] row. So essentially if the flip of the first two columns exists, keep it, and if not, flip the first two columns, keep the values for the rest of the olumns, and add as a new row. For example, if I have matrix A, I want to produce B.
A = [1 2 5 6 0 2 3 5 6 7 0.5 8 0
2 1 7 6 2 0 2 0 0 1 1 1 1 1
3 5 0 1 5 8 2 0 0 2 3 0 9 0.1
4 5 3 6 4 1 7 0 0 1 4 2 1 -2
2 3 0 1 0 1 8 8 2 0 1 5 5 5
3 2 2 5 6 7 1 2 4 2 0 0 9 -3]
B = [1 2 5 6 0 2 3 5 6 7 0.5 8 0
2 1 7 6 2 0 2 0 0 1 1 1 1 1
3 5 0 1 5 8 2 0 0 2 3 0 9 0.1
5 3 0 1 5 8 2 0 0 2 3 0 9 0.1
4 5 3 6 4 1 7 0 0 1 4 2 1 -2
5 4 3 6 4 1 7 0 0 1 4 2 1 -2
2 3 0 1 0 1 8 8 2 0 1 5 5 5
3 2 2 5 6 7 1 2 4 2 0 0 9 -3]
2 件のコメント
採用された回答
Jan
2022 年 3 月 22 日
編集済み: Jan
2022 年 3 月 22 日
A = [1 2 5 6 0 2 3 5 6 7 1 8 0 2; ... % Value appended!!!
2 1 7 6 2 0 2 0 0 1 1 1 1 1; ...
3 5 0 1 5 8 2 0 0 2 3 0 9 1; ...
4 5 3 6 4 1 7 0 0 1 4 2 1 -2; ...
2 3 0 1 0 1 8 8 2 0 1 5 5 5; ...
3 2 2 5 6 7 1 2 4 2 0 0 9 -3];
A1 = A(:, 1);
A2 = A(:, 2);
[s1, s2] = size(A);
B = zeros(s1 * 2, s2); % Maximum possible output
iB = 0;
for k = 1:s1
Ak = A(k, :);
iB = iB + 1;
B(iB, :) = Ak;
if ~any(A1 == Ak(2) & A2 == Ak(1)) % If A([2,1],k) is no member of A(1:2, :):
iB = iB + 1;
B(iB, :) = [Ak(2), Ak(1), Ak(3:s2)];
end
end
B = B(1:iB, :) % Crop output
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!