MATLAB: Error: Function definitions are not permitted in this context.

error function definition

This is my function
function [ area ] = calcarea(rad )
area = pi*rad.^2
end
When I try to run it, following message shows up, "The selected section cannot be evaluated because it contains an invalid statement
Also, the command window says "Error: Function definitions are not permitted in this context"
What am I doing wrong???

Best Answer

You probably have that function below a script in your m-file. You can't mix a script and a function in the same file. You can have two functions though. So if your file is called test.m, you could have all this in the single file:
function test()
area = calcarea(10)
end
function area = calcarea(rad)
area = pi*rad.^2;
end
Or you could have them in two separate files:
A script in test.m:
area = calcarea(10)
A function in calcarea.m:
function area = calcarea(rad)
area = pi*rad.^2;
end
Related Question