How to sort a part of a given array?
5 views (last 30 days)
Show older comments
Lukas Hablowetz on 7 Dec 2022
I´m looking for a way to sort only a part of a given numeric array in Simulink. Lets say I´ve got an array with 20 elements [20 ... 1]. Depending on the application I just want to sort the first n  entries [20 19 18 17 16] in ascending order, so after the sorting the result of the entire array should look like [16 17 18 19 20 15 14 13...1].
Is there a Simulink block which already has this feature? I´m used to the sort block of the DSP toolbox but this only deals with the entire array at once.
- Solution must be portable to Simulink
- the number n varies during the run-time of my application. It´s a paramter that can be adjust within 1 and 20
- the applicatoin will be converted to a C-Application by the embedded coder so there are also the given C restrictions of fixed array sizes
If there is no block I´d be glad to get any advice, how I could solve this efficiently.
Karim on 7 Dec 2022
Hi, below you can find some example code to demonstrate how to sort the first 'nSort' elements of a given vector.
% create a vector with 20 random integers
MyVec = randi(100,1,20)
% define the number of elements we want to sort
nSort = 5;
% sort the first 'nSort' elements:
MyVec(1:nSort) = sort(MyVec(1:nSort),'ascend')
Jonas on 7 Dec 2022
just use indexing to reassign those numbers
Jonas on 12 Dec 2022
Edited: Jonas on 12 Dec 2022
without beeing familiar with Simulink, there may be a method to split the vector into two parts, sort the first part and combine them again?
this could be suitable?
Find more on Array and Matrix Mathematics 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!