Clear Filters
Clear Filters

How to - "sort" using mexCallMATLAB ?

1 view (last 30 days)
Rajaram B S R
Rajaram B S R on 1 Nov 2011
Dear all,
I am writing a mex-function and need to sort some data using the mexCallMATLAB API so that I get the data in the required form. i.e I need the data in descending order along with the index values.
In matlab - [y,i] = sort(x,1,'descend'); does the job for me. Can I simulate the same through the mexCallMATLAB API? If yes, how does it fit in the syntax for the API?
or
Should I write a C-code for the same?
Thanks in advance

Accepted Answer

Jan
Jan on 1 Nov 2011
Using a quicksort in C directly might be more efficient. Especially if your data set is small, the overhead of calling Matlab will be important. For large data sets it matters, that Matlab's SORT is highly efficient and mexCallMATLAB could be the best choice:
mxArray *In[3];
mxArray *Out[2];
In[0] = <your data>;
In[1] = mxCreateDoubleScalar(1.0);
In[2] = mxCreateString("descend");
mexCallMATLAB(2, Out, 3, In, "sort");
  4 Comments
Rajaram B S R
Rajaram B S R on 1 Nov 2011
Hi Kaustaubha,
Thank you very much!
Can you tell me why mxCalloc does not work here?
Jan
Jan on 1 Nov 2011
mxCalloc allocates bare bytes in the memory. mxCreateDoubleMatrix creates a Matlab variable of type DOUBLE. This has additional fields for the dimensions, a pointer to the real and imaginary data, and a lot of further information.

Sign in to comment.

More Answers (1)

Kaustubha Govind
Kaustubha Govind on 1 Nov 2011
Yes, you should be able to call into the MATLAB 'sort' implementation using mexCallMATLAB. Whether or not to implement your own algorithm in C is subjective. There is potential for performance improvement in some cases because MATLAB functions are interpreted and there is overhead for data marshaling, but it appears that the MATLAB sort is multithreaded, so you might not be able to do any faster than MATLAB can, unless you plan to call into some highly-optimized libraries. If performance is very important to you, perhaps you should perform some benchmarking to see if the MATLAB implementation is good enough for your application.

Community Treasure Hunt

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

Start Hunting!