MATLAB: Error: Function definition not supported in this context. Create functions in code file.

errorfunctionmatlab function

Hello,
I was trying to create a simple function on matlab, I already have a file named "AddOne.m", so it should work, however at the first line of code, matlab throws the following error
"Error: Function definition not supported in this context. Create functions in code file.". Any ideas how to sort this out?
Thanks in advance!
matlab pifiando la funcion.png

Best Answer

Hi Augstin,
In matalb, you need to write your function in a seperate matlab file and then you can call this function either from command window or from a seperate matlab file.
For example, here you can write your matlab function addOne.m in one file. File content can be something like:
%File addOne.m
function finalAnswer = addOne(inputNumber)
finalAnswer = inputNumber+1;
end
Now you can use this function in your other matlab file or in command window. For example, you can create a seperate file to call this function.
% File testaddOne.m
inputNumber = 5;
finalAnswer = addOne(inputNumber);
disp('Thining...');
fprintf('Final Answer: %d \n', finalAnswer);
display('Done');
To avoid confusion, for now keep both files at one place. When you run file testaddOne.m, it will automatically call other file and make use of it.
Cheers.