How to insert elements in a heap
조회 수: 13 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
James Tursa
2016년 10월 31일
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?
댓글 수: 10
추가 답변 (1개)
Alexandra Harkai
2016년 10월 31일
BinMinHeap(n)=ElementsToInsert(n)
BinMinHeap(n)=deal(ElementsToInsert(n))
However, there will be problems with this still, because the comparison is not a valid operation on structs:
BinMinHeap(n)<=BinMinHeap(n-1)
so you could compare the keys instead:
BinMinHeap(n).key<=BinMinHeap(n-1).key
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!