参考链接:吴恩达老师机器学习第二周资源
1.什么是Octave
- Wikipedia
GNU Octave是一种采用高级编程语言的主要用于数值分析的软件。
- Zfancy
Octave是一种开源软件,Matlab的有效替代。在实现机器学习算法过程中,可先用Octave初步实现,后再用其他编程语言(如python)改写,可提高开发效率。
笔者为了完成上述参考链接课程中实现机器学习算法的的需要,初步学习了Octave操作,与诸君共享!
2.Octave基本语法
基本操作
- 改变提示风格:
PS1('...') %...表示自己喜欢的提示符号
- 路径
cd 'path' %改变到path路径
addpath 'path' %添加路径
ls %unix风格命令,显示当前路径下的内容
pwd %unix风格命令,显示当前路径
- 算数和逻辑运算
2^6 %幂运算
1 == 2 % flase
1 ~= 2 % true 不等于
1 && 2
1 || 2
xor(1,2)
- 输出变量
a=12 %不加分号即输出
disp(a)
disp()
disp(sprintf('2 decimals: %0.2f', a)) %C语言风格
- 矩阵和向量示例
A = [ 1 2 ; 3 4 ; 5 6] %3*2矩阵
v = [1 2 3] %行向量
v = [1 ; 2 ; 3] %列向量
v = 1:0.1:6 %行向量
A(a:b,c:d) %取矩阵元素
p(i) %取向量元素也可以用这种方法
- 生成矩阵
A = eye(5) %单位矩阵
A = ones(2,3) %全一矩阵
A = zeros(2,3) %全零矩阵
A = rand(2,3) %随机矩阵
A = randn(2,3) %符合高斯分布的随机矩阵
- 提取矩阵元素
%% indexing
A(3,2) % indexing is (row,col)
A(2,:) % get the 2nd row.
% ":" means every element along that dimension
A(:,2) % get the 2nd col
A([1 3],:) % print all the elements of rows 1 and 3
A(:,2) = [10; 11; 12] % change second column
A = [A, [100; 101; 102]]; % append column vec
A(:) % Select all elements as a column vector.
- 矩阵和向量运算
A*C %矩阵乘法
A.*C %对应元素相乘
A.^2 %每一元素平方
1./A %每一元素取倒数
length(v) %计算向量长
size(A,1);size(A,2) %计算矩阵维度
[val,index] = max(A) %计算矩阵最大值及对应下标
sum,prod %求和、求乘积
pinv(A) %求矩阵逆
条件语句
- if
if v==1,
disp('yes');
elseif v==2,
disp('no');
else
disp('what?');
endif
循环语句
- for
v = zeros(10,1);
for i=1:10,
v(i) = 2^i;
end;
- while
i = 1;
while true,
v(i) = 999;
i = i+1;
if i == 6,
break;
end;
end
函数
- 声明
function [y1, y2] = squareandCubeThisNo(x)
y1 = x^2
y2 = x^3
- 调用
[a,b] = squareandCubeThisNo(x)
数据处理
- 加载数据
load q1y.dat % alternatively, load('q1y.dat')
load q1x.dat
- 加载后的数据在变量列表里,可通过以下命令查看
who % list variables in workspace
whos % list variables in workspace (detailed view)
- 通过以下命令清除特定变量
clear q1y
- 保存文件
save hello.mat v; % save variable v into file hello.mat
save hello.txt v -ascii; % save as ascii
绘图
- 基本绘图
%% plotting
t = [0:0.01:0.98];
y1 = sin(2*pi*4*t);
plot(t,y1);
y2 = cos(2*pi*4*t);
hold on; % "hold off" to turn off
plot(t,y2,'r');
axis([0.5 1 -1 1]); % change axis scale
xlabel('time');
ylabel('value');
legend('sin','cos');
title('my plot');
print -dpng 'myPlot.png'
close; % or, "close all" to close all figs
- 子图
figure(1); plot(t, y1);
figure(2); plot(t, y2);
figure(2), clf; % can specify the figure number
subplot(1,2,1); % Divide plot into 1x2 grid, access 1st element
plot(t,y1);
subplot(1,2,2); % Divide plot into 1x2 grid, access 2nd element
plot(t,y2);