美文网首页
Loop and Function

Loop and Function

作者: LinKuriboh | 来源:发表于2019-03-26 20:10 被阅读0次

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

相关文章

网友评论

      本文标题:Loop and Function

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