Nested function: FUNCTION keyword use is invalid here. This might cause later messages about END
12 views (last 30 days)
Show older comments
amateurintraining
on 20 Oct 2017
Commented: amateurintraining
on 20 Oct 2017
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 Comments
Accepted Answer
Walter Roberson
on 20 Oct 2017
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.
More Answers (0)
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!