How to write a function

1 view (last 30 days)
Jack Ellis
Jack Ellis on 21 Nov 2019
Commented: Jack Ellis on 21 Nov 2019
Hi guys,
Im new to matlab. Im tyring to write a function for standard deviation. Ive got the following:
function output=Standard_deviation(A)
n=length(A);
mean=sum(A)/n;
Top=sum(A-mean);
Output=sqrt(Top/n);
end
It is telling me that Standard_deviation is not defined. Please could someone explain how to set function codes up properly

Answers (2)

James Tursa
James Tursa on 21 Nov 2019
Edited: James Tursa on 21 Nov 2019
MATLAB is case sensitive, Output is not the same variable as output. Also, you need to square the Top value, and depending on which formula you are using, you might need to divide by n-1 instead of n.
As an aside, it is better to use variable names that don't clash with MATLAB standard function names. Since MATLAB already has a function called mean, a better choice for you variable might be Amean.
  1 Comment
Jack Ellis
Jack Ellis on 21 Nov 2019
Hi,
Thank you for getting back to me. Ive chnaged it to this;
function output=Standard_deviation(A)
n=length(A);
Amean=sum(A)/n;
Top=sum((A-Amean)^2);
output=sqrt(Top/(n-1));
end
Its now telling me there is an issue with the forth line

Sign in to comment.


Steven Lord
Steven Lord on 21 Nov 2019
What's the name of the file in which you saved this function? If the function name and the file name are different, MATLAB knows the function by the file's name. So if you saved this in ellis_standard_deviation.m even though the first line is "function output=Standard_deviation(A)", to call it in MATLAB you'd need:
M = magic(4);
theStandardDeviation = ellis_standard_deviation(M)
If you're writing your code in the MATLAB editor and you have a function/file name mismatch, Code Analyzer will warn you about the mismatch. Look for the orange line in the right gutter. If you right-click on the text underlined in orange on that line it'll even offer to correct the mismatch for you.
  1 Comment
Jack Ellis
Jack Ellis on 21 Nov 2019
Hi,
Ive saved the file as Standard_deviation. The right hand column is all green. It keeps telling me there is an issue with line 4 but im not sure why?

Sign in to comment.

Categories

Find more on Programming 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!