>> v = zeros(10,1)
v =
0
0
0
0
0
0
0
0
0
0
>> for i=1:10,
> v(i) = 2^i;
> end;
>> v
v =
2
4
8
16
32
64
128
256
512
1024
>> indices = 1:10
indices =
1 2 3 4 5 6 7 8 9 10
>> for i=indices,
> disp(i);
> end;
1
2
3
4
5
6
7
8
9
10
>> i = 1;
>> while i<=5,
> v(i) = 100;
> i++;
> end;
>> i=1;
>> while true,
> v(i) = 999;
> i++;
> if i==6,
> break;
> end;
> end;
>> if v(1)==1,
> disp('The value is one');
> elseif v(1)==2,
> disp('The value is two');
> else
> disp('The value is not one or two');
> end;
函数,需要先建一个.m文件:
function y = squareThisNumber(x) %文件名和函数名一样
y = x^2;
>> squareThisNumber(5) %调用函数
ans = 25
将代码文件所在路径添加到Octave系统搜索路径中:
这样即使你在别的路径下,也可以调用代码文件所在路径下的文件函数了。
>> addpath('C:\Users\mei\Workspaces\Octave_codes')
多返回值函数:
function [y1,y2] = squareAndCubeThisNumber(x)
y1 = x^2;
y2 = x^3;
>> [y1,y2] = squareAndCubeThisNumber(2) %调用函数
y1 = 4
y2 = 8
应用举例:简单的训练数据集:
>> X = [1 1; 1 2; 1 3]
X =
1 1
1 2
1 3
>> y = [1; 2; 3]
y =
1
2
3
编写代价函数 costFunctionJ.m:
function J = costFunctionJ(X, y, Theta)
% X is the "design matrix" containing our training examples.
% y is the class labels
% Theta is the Hypothesis's parameters is a vector.
m = size(X, 1) % number of training examples
predictions = X*Theta; % predictions of hypothesis on all m examples
sqrErrors = (predictions-y).^2; % square errors
J = 1/(2*m) * sum(sqrErrors);
假设我们已训练好了参数:
参数为0,1时:
>> Theta = [0; 1] % h = 0 + 1*x
Theta =
0
1
>> j = costFunctionJ(X,y,Theta)
m = 3
j = 0
%代价为0,说明该Theta参数用在假设函数上,假设函数和训练数据集拟合的很好
我们将参数设置为0,0,验证一下我们写的代价函数的正确性:
>> Theta = [0; 0] % h = 0 + 0*x
Theta =
0
0
>> j = costFunctionJ(X,y,Theta)
m = 3
j = 2.3333 %参数都为0时误差这么大
>> sum((0-y).^2)/(2*3) %假设函数为0时,代价就是这么算的
ans = 2.3333 %验证正确