MATLAB: How to insert elements in a heap

elementsheapnonscalar struct arraystruct

I am trying to insert elements on to a heap with the code below but get error "conversion to double from struct not possible"
ElementsToInsert = [];
ElementsToInsert(1).pos = [3,1]; ElementsToInsert(1).key = 4;
ElementsToInsert(2).pos = [3,2]; ElementsToInsert(2).key = 2;
ElementsToInsert(3).pos = [3,3]; ElementsToInsert(3).key = 1;
ElementsToInsert(4).pos = [4,2]; ElementsToInsert(4).key = 3;
BinMinHeap = [];
for n=1:1:length(ElementsToInsert)
%insert ElementsToInsert(n) at the end of the heap
BinMinHeap(n)=ElementsToInsert(n)
while BinMinHeap(n)<=BinMinHeap(n-1)
swap(BinMinHeap(n),BinMinHeap(n-1))
%BinMinHeap(n)=BinMinHeap(n-1)
...;
end
end

Best Answer

You can clear the variables instead of initializing them to empty doubles. E.g.
% ElementsToInsert = [];
clear ElementsToInsert % <-- clear the variable
But then you will run into an error using the index n-1 when n=1 in your loop. So maybe make this change also:
% BinMinHeap = [];
BinMinHeap = ElementsToInsert(1); % <-- Initialize to 1st element
for n=2:1:length(ElementsToInsert) % <-- Starting index changed from 1 to 2
Then you will run into an error on this line for comparing structs:
while BinMinHeap(n)<=BinMinHeap(n-1)
To fix this, I don't know what you really want to compare here. Maybe the key? E.g.,
while BinMinHeap(n).key<=BinMinHeap(n-1).key
But even with this change, I have to wonder why you have this in a while loop. Are you intending to bubble the latest entry up to its appropriate spot? If so, you will need to change the indexing you use in this while loop.
Then this line looks suspicious:
swap(BinMinHeap(n),BinMinHeap(n-1))
It appears you want to swap two element of BinMinHeap, but calling a function for this likely will not do what you intend since functions in general work with copies of the inputs. Maybe you meant this?
% swap(BinMinHeap(n),BinMinHeap(n-1))
temp = BinMinHeap(n);
BinMinHeap(n) = BinMinHeap(n-1);
BinMinHeap(n-1) = temp;
Are you trying to code up a simple insertion or bubble sort?