Loop and Function

Attention: all loop statement need an 'end';

  • For:
for <condition>,
    <statement>;
end;
  • While:
while <condition>,
    <statement>;
end;
  • if:
if <condition>,
    <statement>;
elseif <condition>;
    <statement>;
else <condition>;
    <statement>;
end;
  • pwd: to show the current path:
octave:1> pwd
ans = /Users/xxx
  • addpath: to tell Octave an additional path to find codes
octave:2> addpath('/Users/xxx/yyy')
  • To write a function and use it:
  1. Define a function in another file with extension .m .
%filename is costFunctionJ.m

function J = costFunctionJ(x, y, theta)

% x is the 'design matrix' contains our training examples.
% y is the class lables

m = size(x, 1);                     %number of training samples
predictions = x * theta;            %prediction of hypothesis on all m examples
sqrErrors = (predictions - y) .^ 2; %squared errors

J = 1/(2 * m) * sum(sqrErrors);
  1. Call it in Octave:
octave:4> x = [1 1; 2 2; 3 3]
x =

   1   1
   2   2
   3   3

octave:5> y = [1; 2; 3]
y =

   1
   2
   3

octave:6> theta = [0; 1]
theta =

   0
   1

octave:9> j = costFunctionJ(x, y, theta)
j = 0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,448评论 0 10
  • 1、每天坚持去做好工作日志记录,形成记录电子版本。对电子版本施行色彩管理学的应用,逐步改善自己完善自我。 每月做一...
    尺寸元角分阅读 670评论 0 2
  • 暮暮秋少长,丝丝点点已泛黄,犹如霓罗裳。朝朝月明生,零零碎碎欲断魂,不应有情,何似照人间?梦如落花情如雨,喟叹年华...
    南港孤魂阅读 345评论 0 0
  • 人家只是随便勾搭你好不好。你就上岸了。我真的服了你。人家根本不喜欢你。
    只是找一个地方码子_阅读 60评论 0 0
  • Ubuntu文件操作随记 创建文件touch test.txt 编辑文件vi test.txt显示编辑窗口按“i”...
    前途很嘿暗阅读 423评论 0 1