## How to write a function

Jack Ellis

### Jack Ellis (view profile)

さんによって質問されました 2019 年 11 月 21 日 20:25

### Jack Ellis (view profile)

さんによって コメントされました 2019 年 11 月 21 日 22:13
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

#### 0 件のコメント

サインイン to comment.

## 2 件の回答

### James Tursa (view profile)

on 21 Nov 2019 at 20:28
Edited by James Tursa

### James Tursa (view profile)

on 21 Nov 2019 at 20:32

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.

Jack Ellis

### Jack Ellis (view profile)

on 21 Nov 2019 at 20:42
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

サインイン to comment.

### Steven Lord (view profile)

on 21 Nov 2019 at 21:08

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.

Jack Ellis

### Jack Ellis (view profile)

on 21 Nov 2019 at 22:13
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?

サインイン to comment.

Translated by