I need a min-heap in Matlab and I'm trying to use Java's PriorityQueue. I'm stuck on how to supply the Comparator. So far I have initialized the PriorityQueue and can add one value-index pair to it:
>> q = java.util.PriorityQueue
q =
[]
>> q.add({1,3})
ans =
1
The problem occurs when I try to add more data:
>> q.add({2,4})
??? Java exception occurred:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.lang.Comparable
at java.util.PriorityQueue.siftUpComparable(Unknown Source)
at java.util.PriorityQueue.siftUp(Unknown Source)
at java.util.PriorityQueue.offer(Unknown Source)
at java.util.PriorityQueue.add(Unknown Source)
From this post, I see that I need to supply a Comparator function, but I don't know how to do this.
Priority queues need to either contain objects that implement Comparable, or you need to pass in a Comparator function at construction time.
There isn't a way currently in MATLAB to either implement Java interfaces with MATLAB code, or supply literal Java code.
So you'd have to follow @nibot's suggestion and make a small .jar file containing a class implementing Comparator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With