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:
- 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);
- 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