How to write a function

1 回表示 (過去 30 日間)
Jack Ellis
Jack Ellis 2019 年 11 月 21 日
コメント済み: Jack Ellis 2019 年 11 月 21 日
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

回答 (2 件)

James Tursa
James Tursa 2019 年 11 月 21 日
編集済み: James Tursa 2019 年 11 月 21 日
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 件のコメント
Jack Ellis
Jack Ellis 2019 年 11 月 21 日
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

サインインしてコメントする。


Steven Lord
Steven Lord 2019 年 11 月 21 日
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 件のコメント
Jack Ellis
Jack Ellis 2019 年 11 月 21 日
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?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by