Help with a nested loop
Afficher commentaires plus anciens
I am trying to create a function which loops through a data set by comparing each row to every other row, and returning a variable if a relationship between the two rows is true (in this case, a distance relationship). The function starts at row 2 and compares 2 to 3, 3 to 4, and so on, before the outer loop increases the starting row by 1, and then the function compares row 3 to row 2, row 3 to row 4, and so on, until every row is compared with every other row.
Currently, if I run this function without the outer loop, it seems to work fine. When I nest the inner loop in the outer loop to move the reference row by 1, it is not longer working properly.
There are two specific issues:
- The nested loop I have written currently returns the entire vector of the variable I want returned only if the relationship between two rows is true. So if I tell the function to return x when the relationship is true, it is currently just returning the entire vector of x.
- It is returning the entire vector of x as one long row. I would like it to return x (when the statement is true) but start a new row each time the outer loop repeats. So I end up with rows corresponding to all the values of x when I compared to row 2, a row of all the values when I compared to row 3, and so on.
Any help is much appreciated. I am still learning Matlab. Thank you. Here is the relevant chunk of code:
function [out] = EMA_location_compare(OutputVariable, Dist, xCartCoor, yCartCoor)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
len = length(xCartCoor); %number of rows
for n = 2:len %index reference row
for v = 2:len %index comparison row
if v == n
continue %skip iterations where n is compared with itself
elseif v ~=n
ipd = sqrt((xCartCoor(n) - xCartCoor(v))^2 + (yCartCoor(n) - yCartCoor(v))^2); %pythogrean distance
ipd = ipd * 1000; %convert kl to meters
if ipd <= (Dist) %if statement to define distance constraint
out(v) = OutputVariable(v); %output variable
end
end
end
end
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!