How to check for reversed pairings in columns of a matrix?

1 vue (au cours des 30 derniers jours)
Emma Kuttler
Emma Kuttler le 22 Mar 2022
Modifié(e) : Jan le 22 Mar 2022
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 commentaires
Jan
Jan le 22 Mar 2022
Modifié(e) : Jan le 22 Mar 2022
B ist not "a smaller matrix". Do you mean "a larger matrix"?
The first row of A contains less elements than the others. The same for B.
Emma Kuttler
Emma Kuttler le 22 Mar 2022
@Jan , edited! I meant larger

Connectez-vous pour commenter.

Réponse acceptée

Jan
Jan le 22 Mar 2022
Modifié(e) : Jan le 22 Mar 2022
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
B = 8×14
1 2 5 6 0 2 3 5 6 7 1 8 0 2 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 5 3 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 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

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by