Sorting pairs into seperate matrices based on whether they are ascending or descending

9 visualizaciones (últimos 30 días)
I have a 10x2 matrix of pairs of numbers
pairs = 10×2
2 8
7 5
6 8
4 7
8 6
2 5
4 2
6 2
1 7
3 1
And I wish to seperate them into two different nx2 matrices depending on whether the pairs are ascending or descending
%Seperates ascending and descending pairs
asc=ones(length(pairs),2);
desc=ones(length(pairs),2);
i=2
for i=1:(length(pairs))
diff=diff(pairs(i,:));
if diff>0
asc=asc(i,:).*pairs(i,:);
else
desc=desc(i,:).*pairs(i,:);
end
end
However everytime i try to run the for loop it returns the "Index exceeds the number of array elements" error.
I tried running it without the loop and it works until i run it again and this error appears. What am i doing wrong?

Respuesta aceptada

Star Strider
Star Strider el 23 de Nov. de 2023
The loop is not necessary anyway.
Just use ‘logical indexing’ —
pairs = [2 8
7 5
6 8
4 7
8 6
2 5
4 2
6 2
1 7
3 1];
Lv = pairs(:,2) > pairs(:,1)
Lv = 10×1 logical array
1 0 1 1 0 1 0 0 1 0
asc = pairs(Lv,:)
asc = 5×2
2 8 6 8 4 7 2 5 1 7
desc = pairs(~Lv,:)
desc = 5×2
7 5 8 6 4 2 6 2 3 1
.

Más respuestas (1)

Dyuman Joshi
Dyuman Joshi el 23 de Nov. de 2023
Firstly, do not use built-in functions as variables (or script) names, like you have done here -
diff=diff(pairs(i,:));
Secondly, the default operating dimension of diff() is to find difference of successive elements along the rows.
To work through the difference of columns, you need to specify the dimension -
pairs = [2 8
7 5
6 8
4 7
8 6
2 5
4 2
6 2
1 7
3 1];
%Find the (1st) difference along columns
idx = diff(pairs, 1, 2)>0
idx = 10×1 logical array
1 0 1 1 0 1 0 0 1 0
%Use logical indexing to get the ascending and descending pairs, respectively
asc = pairs(idx, :)
asc = 5×2
2 8 6 8 4 7 2 5 1 7
desc = pairs(~idx, :)
desc = 5×2
7 5 8 6 4 2 6 2 3 1

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by