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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,854評論 0 10
  • 1、每天堅(jiān)持去做好工作日志記錄,形成記錄電子版本。對電子版本施行色彩管理學(xué)的應(yīng)用,逐步改善自己完善自我。 每月做一...
    尺寸元角分閱讀 725評論 0 2
  • 暮暮秋少長,絲絲點(diǎn)點(diǎn)已泛黃,猶如霓羅裳。朝朝月明生,零零碎碎欲斷魂,不應(yīng)有情,何似照人間?夢如落花情如雨,喟嘆年華...
    南港孤魂閱讀 383評論 0 0
  • 人家只是隨便勾搭你好不好。你就上岸了。我真的服了你。人家根本不喜歡你。
    只是找一個地方碼子_閱讀 70評論 0 0
  • Ubuntu文件操作隨記 創(chuàng)建文件touch test.txt 編輯文件vi test.txt顯示編輯窗口按“i”...
    前途很嘿暗閱讀 441評論 0 1

友情鏈接更多精彩內(nèi)容