matlab用于机器学习里的基础语法
也是吴恩达机器学习第6章Octave/Matlab 教程中讲解用的基础程序
5+6
2^6
1==2
1~=2
1&&0
1||0
xor(0,1)
a = pi;
disp (sprintf ('2 decimals : %0.2f ' , a ))
disp (sprintf ('6 decimals : %0.2f ' , a ))
disp (sprintf ('6 decimals : %0.6f ' , a ))
format long
a
format short
a
A = [1 2 ; 3 4 ; 5 6]
size(A) %3 2
ZA = size(A)
size(ZA) %1 2
size(ZA,1) %3 size(ZA,2) 2
v = 1:0.1 :2
V = [1;2;3]
c = ones(2,3)
rand(1,3)
rand(3,3)
w = -6+sqrt(10)*randn(1,1000);
hist(w)
hist(w,50)
eye(4)
v = [1,2,3,2,1]
length(v) %5
length(A) %较大的维度为3 则输出3
pwd %当路前径
cd('/Users/Mac/Documents/MATLAB') %修改路径
data = load('ex1data1.txt');
who
size(ex1data1)
whos
A(3,2) %6
A(2,:) % :获得第二行所有元素
A(: , 2) % :获得第二列所有元素
A([1 3],:)% :获得第1,3行所有元素
A(: , 2)= [10;11;12]
%A = 1 10; 3 11; 5 12 把第二列赋值
A = [A, [100;101;102]] %A = 1 10 100; 3 11 101; 5 2 102加值
A(:) % put all elements of A into a single vector
A = [1 2 ; 3 4 ; 5 6]
B = [11 12 ;13 14; 15 16]
C = [1 1 ; 2 2]
A * C % 矩阵相乘
A .* B %矩阵对应位置相乘
A .^ 2
v = [1;2;3]
1 ./ v
log(v)
exp(v)
abs(v) %绝对值
-v
v + ones(length(v),1) % ones(行,列)
v + 1
A' %转置
pinv(A) %伪逆
a = [1 15 2 0.5 ]
val = max(a) %z必须小写
[val, ind] = max(a) % ind是这个 值的索引
A = magic(3) %九宫格
[r , c ] = find(A >= 7)
%r= 1 3 2 c = 1 2 3 即a11 , a32 , a23
sum(a) %和
prod(a) %积
floor(a) %向下取整
ceil(a) %向上取整
max(A , [] , 1) % 每一列的最大值
max(A , [] , 2) % 每一行的最大值
max(max(A)) max(A:) %取矩阵最大值
A = magic(9) sum (A ,1)%行和
sum (A ,2) %列和
sum(A*eye(9)) %对角线和
t = [0 : 0.01 : 0.98];
y1 = sin(2*pi*4*t);
plot(t, y1 )
y1 = sin(2*pi*4*t);
y2 = cos(2*pi*4*t);
figure(2);plot(t ,y1)
hold on;
figure(1); plot(t ,y2 , 'r')
xlabel('time')
ylabel('value')
legend('sin','cos')
title('my plot')
cd '/Users/Mac/Documents/MATLAB' ; print -dpng 'myplot.png'
close %画图并保存关闭图
figure(2);plot(t ,y1)
figure(1); plot(t ,y2 , 'r')
subplot(1,2,1);% Divides plot a 1x2 grid, access first element
plot(t ,y1)
subplot(1,2,2);
plot(t ,y2 , 'r')
% 一张图上有两部分,左边画y1 右边画y2
axis([0.5 1 -1 1]) % g把右表的横坐标轴变为(0.5 1)纵坐标轴变为(-1 1)
clf %清除图里的内容
A = magic(5)
imagesc(A) % 把矩阵用图像颜色可视化
imagesc(A) , colorbar , colormap gray; %colorbar 颜色条 ,灰色图
imagesc(magic(15)) , colorbar , colormap gray;
v = zeros(10,1)
for i = 1:10,
v(i) = 2^i;
end;
v
indices = 1:10;
indices
or i = indices,
disp(i);
end;
i = 1 ;
while i <= 5,
v(i) = 100;
end;
v
i=1;
while true.
v(i) = 999;
i= i+1;
if i == 6,
break;
end;
end;
v
if v(1) == 1;
disp('The value is one');
elseif v(1) == 2,
disp('The value is two');
else
dosp('The value is not one or two.');
end;