How to exempt an index of an array from a loop after each iteration?
Show older comments
I have two arrays called array and newarray. Both are of size N X sz. The first column of array is the first column of newarray. I have a loop that goes through each value of array looking at each row of each column (2nd column onwards), and it finds the value (index) from the previous column which is closest. The code is below. However, some of the values in the columns are the same and I do not want an index from the previous column to be matched more than once. How do I exempt an index from being chosen again if it already has a match from the previous iteration?
newarray(1:N,1) = array(1:N,1);
for j = 1:1:sz-1
for s = 1:1:N
BestDistance = 10;
A = newarray(s,j);
for k = 1:1:N
B = array(k,j+1);
Distance = abs(B-A);
if Distance < BestDistance
BestDistance = Distance;
BestMatch = k ;
%If the index k has already been matched previously, I want it to be exempt from being chosen again
end
end
newarray(s,j+1)=array(BestMatch,j+1);
end
end
Answers (1)
Star Strider
on 14 Jan 2017
0 votes
Without actually having both ‘array’ and ‘newarray’, it’s not possible to write specific code.
See if the find, ismember (or ismembertol) functions will do what you want.
10 Comments
Star Strider
on 14 Jan 2017
At least an example of the arrays you’re starting with and the result you want could be helpful.
I still don’t understand exactly what you want. Your last Comment suggests that the unique (or uniquetol) functions could work.
Star Strider
on 14 Jan 2017
OK, so what do you do next? Choose 0 because it’s closest to 2, just stop, or choose something else (and with what criteria)?
The ismember functions works best for integers. If you have floating point numbers (or ‘integers’ that were calculated from floating-point numbers), rounding them to integers or using ismembertol work best.
belle
on 14 Jan 2017
Star Strider
on 14 Jan 2017
OK. You have complex numbers as indices? How does that work? How do you define ‘distance’?
Pardon me, but the more I learn about what you want to do, the less I understand.
belle
on 14 Jan 2017
Star Strider
on 14 Jan 2017
I understand distance with respect to the integer indices. My question was about distance with respect to the complex numbers.
You can also use the setdiff function to eliminate indices you’ve already chosen, returning only those that are still ‘eligible’. You have to keep track of those you’ve already chosen in a vector to use them with the setdiff function. That might make choosing the others easier.
Star Strider
on 14 Jan 2017
My pleasure.
Now I’m completely confused. I have no idea how the distances and indices interact.
I’m happy you got this sorted. You have a good weekend, too.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!