How can I rectify this: Error: Function definitions are not permitted in this context.

Hello,
Full disclosure, I am a completely newbie to Matlab and am currently enrolled in an introductory course. I have an assignment for which I must create a function that uses the bubble sorting algorithm to sort a 1xn matrix in ascending order. I have already created and tested my code but I am having difficulty saving and running it as an actual function. I am using the online Matlab software currently.
Here is my attempt:
function A = bubble_sort(A)
% SUMMARY: BUBBLE_SORT Sorts a matrix A in ascending order using the bubble sort algorithm.
% INPUT is a 1xn matrix A
% OUTPUT is the sorted (ascending) version of A
while ~isSorted(A)
for i = 1:length(A)-1
if A(i) > A(i+1)
temp = A(i);
A([i i+1]) = A([i+1 i]);
temp = A(i+1);
end
end
end
end
Everytime I attempt to run it, I get the following error:
" function A = bubble_sort(A)
Error: Function definitions are not permitted in this context.
"
Any help or clarification would be greatly appreciated. Thanks so much!
Best, Steven

Answers (1)

It is a good idea to search in the forum before asking. You would find the solution fast: In older Matlab versions, functions can be define in "function files" only: M-files, which start with the keyword "function". If an M-file is a script (Matlab code without the leading keyword "function"), you cannot define a function in this file. In the command window, functions cannot be defined also.
So all you have to do is write the show code snippet to a file. Open the editor, paste the code, save it.
Note that "I attempt to run it" is not clear. If the code is saved to a function file, you run it by calling from another function, or script, or from the command window by:
ASorted = bubble_sort(A)

Categories

Asked:

on 9 Nov 2017

Edited:

Jan
on 9 Nov 2017

Community Treasure Hunt

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

Start Hunting!