Sort columns to get the lowest possible difference in every row

4 visualizaciones (últimos 30 días)
Josip Strutz
Josip Strutz el 3 de Jun. de 2021
Comentada: David Hill el 3 de Jun. de 2021
I got a matrix A with the X-Positions of local maximas (A(:,1)) and minimas ((A(:;2). As you can see in the vector B the difference between the rows is getting bigger as the X-Position is rising, but I need them as near as possible to each other - independent of the rownumber. If there is no suitable minima to the maxima within a range of 20 then the found local peaks are useless for the further coding (maybe declare as NaN?).
How can I sort the columns in A to get the lowest possible difference in every row? A brute force solution doesn't fit for a dataset of >200.000 points.
A = [15 18.7500000000000;19 24;24 28.5000000000000;31 35;40 41.5000000000000;50 49.2500000000000;59 58.2500000000000;68 67.7500000000000;74.6666666666667 79.5000000000000;81 92.2500000000000;85.3333333333333 103.500000000000;94 112.500000000000;102 118.250000000000;110 122.750000000000;113.666666666667 128.750000000000;119 140.750000000000;126.666666666667 153.500000000000;136.333333333333 166.750000000000;145 180.750000000000;151.333333333333 190;156.333333333333 200;162 210.750000000000;173 220.250000000000;187 228.250000000000;200.666666666667 234.750000000000]
B = [3.75000000000000;5;4.50000000000000;4;1.50000000000000;-0.750000000000000;-0.750000000000000;-0.250000000000000;4.83333333333333;11.2500000000000;18.1666666666667;18.5000000000000;16.2500000000000;12.7500000000000;15.0833333333333;21.7500000000000;26.8333333333333;30.4166666666667;35.7500000000000;38.6666666666667;43.6666666666667;48.7500000000000;47.2500000000000;41.2500000000000;34.0833333333333]
Thank you in advance.

Respuestas (1)

David Hill
David Hill el 3 de Jun. de 2021
A for-loop can go through 200,000 cycles quite fast. Not sure there is an easiler way.
a=A(:,1);
b=A(:,2);
tol=3;
for k=1:size(A,1)
c=b(b<a(k)+tol&b>a(k)-tol);
if isempty(c)
A(k,2)=nan;
else
A(k,2)=c;
end
end
  2 comentarios
Josip Strutz
Josip Strutz el 3 de Jun. de 2021
Thank you very much, it works. How can I increase the tolerance? If I increase it above 3 it doesn't work anymore.
"Assignment has more non-singleton rhs dimensions than non-singleton subscripts"
David Hill
David Hill el 3 de Jun. de 2021
This code finds the closest value but there could be repeated values used.
a=A(:,1);
b=A(:,2);
tol=3;
for k=1:size(A,1)
[~,idx]=min(abs(a(k)-b));
A(k,2)=b(idx);
end

Iniciar sesión para comentar.

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by