>> v=zeros(10,1) %define 10x1 zero vector
v =
0
0
0
0
0
0
0
0
0
0
>> for i=1:10. % i在[1,10]
v(i)=i*i;
end;
>> v
v =
1
4
9
16
25
36
49
64
81
100
>> indices=1:10;
>> indices
indices =
1 2 3 4 5 6 7 8 9 10
>> for i=indices, %这句话与i=1:10语义相同
disp(i);
end;
1
2
3
4
5
6
7
8
9
10
>> i=1;
>> while i<=5, %while 语句
v(i)=99;
i=i+1;
end;
>> v
v =
99
99
99
99
99
36
49
64
81
100
>> i=1;
>> while true,
v(i)=100;
i=i+1;
if i==8,
break; %使用break语句
end;
end;
>> v
v =
100
100
100
100
100
100
100
64
81
100
>> for i=1:10.
if mod(v(i),2)==0, %取余操作
disp('even');
else
disp('odd');
end;
end;
even
even
even
even
even
even
even
even
odd
even
>> x=9,y=3; %待传参数
x = 9
>>
>> cd 'C:\Users\Administrator\Desktop' %函数文件所在路径,函数文件格式为.m,尝试用写字板打开
>> myfunction(x,y)
ans = 39
>>
下面是myfunction内容: % 返回y值
function y=myfunction(x,z)
y=x+z+x*z;
>> addpath('C:\Users\Administrator\Desktop') %添加过该路径就可以在其它路径下调用该路径下的函数
>> [y1,y2]=myfunction2(x,y)
warning: function name 'myfunction' does not agree with function filename 'C:\Users\Administrator
\Desktop\myfunction2.m'
y1 = 39
y2 = 729
下面是myfunction2内容:
function [y1,y2]=myfunction(x,z) %可以有多个返回值
y1=x+z+x*z;
y2=x^z;
下面内容来自吴恩达机器学习的梯度下降算法:
costFunctionJ函数体:
function J=costFunctionJ(X,y,theta)
% X is the "design matrix" containing our training examples. 输入变量
% y is the class label 输出变量
m=size(X,1); %number of training examples 样本数量
prediction=X*theta; %prediction of hypothesisis on all m examples 假设函数 /拟合函数
sqrError=(prediction-y).^2; %squared errors 单个样本的标准差
J=1/(2*m)*sum(sqrError); %代价函数
拟合函数
代价函数的值越小,则拟合越成功。
下面是对上述函数参数赋值语句:
>> X=[1 1; 1 2; 1 3] %默认X矩阵中第一列都为1
X =
1 1
1 2
1 3
>> y=[1;2;3]
y =
1
2
3
>> theta=[0;1]
theta =
0
1
>> cd 'C:\Users\Administrator\Desktop'
>> J=costFunctionJ(X,y,theta)
J = 0 %J越小则说明拟合函数越好