美文网首页
Octave快速入门(6)——函数

Octave快速入门(6)——函数

作者: 大锅烩菜 | 来源:发表于2018-09-13 11:13 被阅读0次

需要创建一个文件,文件名为函数的名称,后缀为m。例如创建一个名为squareNumber.m文件,内容如下:

% y 是返回值,x是参数。
function  y  = squareNumber(x)
y = x^2;
endfunction     % endfunction可以省略

调用方式如下:

>>cd c:\Users\hyf04
>>squareNumber(5)

执行函数时,需要先切换工作目录到函数文件所在的路径。

函数可以有多个返回值:

function [x,y] = suareAndCube(arg)
  x = arg^2;
  y = arg^3;
endfunction

案例:代价函数:

function J = costFunction(X,y,theta)
  % X is the "design matrix" containing our training examples.
  % y is the class labels
  m  = size(X,1);           % number of training examples
  predictions  = X*theta;   % predictions of hypothesis on all m examples
  sqrErrors = (predictions - y) .^2;  % squared errors
  J = 1/(2*m) * sum(sqrErrors);
endfunction

使用:

>>X =  [1,1;1,2;1,3];
>>y = [1;2;3];
>>theta = [0;1];
>>j = costFunction(X,y,theta)
j = 0

相关文章

网友评论

      本文标题:Octave快速入门(6)——函数

      本文链接:https://www.haomeiwen.com/subject/mjzvgftx.html