Loop and Function

2019-03-26  本文已影响0人  LinKuriboh

Attention: all loop statement need an 'end';

for <condition>,
    <statement>;
end;
while <condition>,
    <statement>;
end;
if <condition>,
    <statement>;
elseif <condition>;
    <statement>;
else <condition>;
    <statement>;
end;
octave:1> pwd
ans = /Users/xxx
octave:2> addpath('/Users/xxx/yyy')
  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
上一篇 下一篇

猜你喜欢

热点阅读