フィルターのクリア

Nested function: FUNCTION keyword use is invalid here. This might cause later messages about END

14 ビュー (過去 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.

採用された回答

Walter Roberson
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 ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by