How to write a function

조회 수: 6 (최근 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 CenterFile Exchange에서 Functions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by