Sorting pairs into seperate matrices based on whether they are ascending or descending
Show older comments
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?
Accepted Answer
More Answers (1)
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
%Use logical indexing to get the ascending and descending pairs, respectively
asc = pairs(idx, :)
desc = pairs(~idx, :)
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!