How to Use sort to Sort an Array of Custom Class Objects in MATLAB?
18 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I have already overloaded the eq, lt, and gt methods in my class definition, but I am still encountering an issue when trying to sort using the sort function.
error sort
Incorrect number or types of inputs or outputs for function sort.
3 comentarios
Respuestas (1)
Divyam
el 16 de Jul. de 2024
Editada: Divyam
el 16 de Jul. de 2024
Hi Jia, ensure that your custom class is defined in a ".m" file with name as the class name. "MyClass.m" has been attached as the reference class for the code below.
To test sorting, the following code was created in a different MATLAB file in the same directory where the class was defined.
% Creating an array of custom class objects
array = [MyClass(5), MyClass(2), MyClass(8), MyClass(3)];
% Extracting the "Value" of the objects in an array using the arrayfun method
valuesExtract = arrayfun(@(obj) obj.Value, array);
% Sorting the values to get the sorted indices
[~, sortedIndices] = sort(valuesExtract);
% Reorder the array based on the sorted indices
sortedArray = array(sortedIndices);
% Displaying the sorted values
for i = 1:length(sortedArray)
fprintf("%d ", sortedArray(i).Value);
end
The issue might be caused by not using "arrayfun" to extract the "Value" property which has to be compared and comparing the property directly.
For more information regarding the use of "arrayfun" method refer to the following documentation: https://www.mathworks.com/help/matlab/ref/arrayfun.html
0 comentarios
Ver también
Categorías
Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!