How can I use nested loops to pair one piece of data with multiple other pieces?

2 vues (au cours des 30 derniers jours)
sid28
sid28 le 16 Juin 2021
Commenté : Stephen23 le 16 Juin 2021
I am currently struggling with the following problem involving looping and pairing data.
I have a table of routes between different regions. Each route is only between a specific region and another specific region. In each region, there are multiple locations. So there are x locations in region A and y locations in region B. I need to pair each location in region A with each location in region B for each route. I know this requires some nested loops, but I am getting lost on how I can properly pair this data.
The problem arises in that there might not be the same number of locations in region A and region B. I'm having trouble looping through this correctly to make sure each location in region A is paired with each location in region B.
To visualize this:
Route 1 has Region A and Region B.
Region A has the following locations: A1, A2, A3.
Region B has the following locations: B1, B2, B3, B4, B5.
I need to essentially have a final result of this:
(A1 -> B1) (A1 -> B2) (A1 -> B3) (A1 -> B4) (A1 -> B5)
(A2 -> B1) (A2 -> B2) (A2 -> B3) (A2 -> B4) (A2 -> B5)
(A3 -> B1) (A3 -> B2) (A3 -> B3) (A3 -> B4) (A3 -> B5)
Does anyone know an efficient way of completing this? Thank you in advance for the help!

Réponse acceptée

KSSV
KSSV le 16 Juin 2021
a = rand(1,3) ;
b = rand(1,5) ;
[B,A] = meshgrid(b,a)
  3 commentaires
KSSV
KSSV le 16 Juin 2021
[A(1,:);B(1,:)]'
Give you the first pair ..and so on..
Stephen23
Stephen23 le 16 Juin 2021
"I need to essentially have a final result of this:"
[A,B] = ndgrid(1:3,1:5);
M = repelem(A,1,2);
M(:,2:2:end) = B;
compose("(A%d -> B%d)",M)
ans = 3×5 string array
"(A1 -> B1)" "(A1 -> B2)" "(A1 -> B3)" "(A1 -> B4)" "(A1 -> B5)" "(A2 -> B1)" "(A2 -> B2)" "(A2 -> B3)" "(A2 -> B4)" "(A2 -> B5)" "(A3 -> B1)" "(A3 -> B2)" "(A3 -> B3)" "(A3 -> B4)" "(A3 -> B5)"
% (A1 -> B1) (A1 -> B2) (A1 -> B3) (A1 -> B4) (A1 -> B5)
% (A2 -> B1) (A2 -> B2) (A2 -> B3) (A2 -> B4) (A2 -> B5)
% (A3 -> B1) (A3 -> B2) (A3 -> B3) (A3 -> B4) (A3 -> B5)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by