Nested function: FUNCTION keyword use is invalid here. This might cause later messages about END
13 次查看(过去 30 天)
显示 更早的评论
I have a function as seen below and am trying to create a nested function:
function [ sortedArray ] = mergeSort( doubleArray )
%UNTITLED2 Summary of this function goes here
% doubleArray: a 1 by N unordered double array to be sorted
% sortedArray: the sorted array of soubleArray
% mergeSort: splits the array into two sub-arrays, recursively sorts the
% two sub-arrays, and then combines the two sorted sub-arrays
A=length(doubleArray);
if A==1
sortedArray=doubleArray;
else
mid=floor(A/2);
array1=mergeSort(doubleArray(1:mid));
array2=mergeSort(doubleArray(mid+1:end));
function combinedArray=combine2Arrays(array1,array2)
combinedArray=[array1, array2];
combinedArray=sort(combinedArray);
end
end
However, I keep getting an error: FUNCTION keyword use is invalid here. This might cause later messages about END.
Does this mean my nested function is incorrect? It is in a function (.m) file NOT script.
0 个评论
采纳的回答
Walter Roberson
2017-10-20
You cannot define a nested function within an "if" or "while" or "switch" or "try/catch" or any other control structure.
Note, by the way, that if your function definition did succeed there, then you would not have invoked the function. And if you did invoke the function, then you would have ended up calling sort() many times. You should not be using sort() at all.
At the time that you are combining two sub-arrays after having sorted the two sub-arrays, then you know that each half has been sorted. That makes it less expensive to do the merge, using techniques such as insertion sort.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!