分享

机器学习 - Matlab 编程常用命令速览

 心不留意外尘 2013-09-14

机器学习- Matlab 编程常用命令速览

--总结自Ng-ML-class Octave/Matlab Tutorial Coursera

from http://blog.csdn.net/yangliuy/article/details/8979793

A、Basic operations and Moving data around
1 在命令行模式用shift + 回车即可附加下一行输出
2 length命令apply到矩阵时返回较高的一维的dimension
3 help + 命令是显示命令的简要帮助信息
   doc + 命令 是显示命令的详细帮助文档
4 who 命令 显示 当前所有创建的变量
   whos 命令 显示当前所有创建变量的详细信息
5 保存变量到.mat 文件save hello.mat b 以二进制压缩保存数据
   save hello.txt v -ascii 以可读形式文件保存 即文本格式
6  :means every elements in this col
7 A([1 3], :) 获取第 1、3两行所有列的数据
8 A = [A, [100; 101; 102]] 在A矩阵后面加一列col vector [100,101,102]
9 size(A) 返回一个1行2列矩阵  表明第1和第2个dimensional 的大小
10 C = [A B]等价于C = [A, B] []为向后面的列添加,连接两个矩阵 [] 为concat 连接矩阵或者字符串
11 C= [A; B] ;号表示向下面行添加,因此会增加相应行数,列数不变

B、Computing on data
12  A.*B是矩阵/向量点乘  A*B是矩阵相乘
13 log(v) 和exp(v)求以e为底的对数和指数
14 abs()求绝对值
15 A‘ 求A的转置矩阵
16 max函数返回矩阵中最大元素的值和索引   [val, ind] = max(a)
17 A < 3 会判断A当中的每一个是否小于3,若小于3,对应位置返回true,否则对于位置返回false
18 find(A<3) 返回矩阵中所有值小于3的索引
19 magic  Magic square.
    magic(N) is an N-by-N matrix constructed from the integers
    1 through N^2 with equal row, column, and diagonal sums.
    Produces valid magic squares for all N > 0 except N = 2.
20  [r, c] = find(A >= 7) 返回值大于等于7的element的row及col的索引
21 prod(a) 求矩阵a里面所有元素的乘积
    floor(a) 对矩阵a中元素向下取整
    ceil(a)对矩阵a中元素向上取整
    rand(3) 生成3X3的随机方阵
    max(A,[],1) 求矩阵A的每一列的最大值(最后一维是1表明为dimension 1)
    max(A,[],2) 求矩阵A的每一行的最大值
    sum(A, 1) 对矩阵A第一维度(即每列)求和(注意matlab中第一维默认是列,然后是行,再然后依次类推。。。)
    sum(A, 2) 对矩阵A第二维度(即每行)求和
    sum(sum(A.*eye(9)))  求矩阵A的对角线元素之和
22 矩阵翻转操作
   flipud  Flip matrix in up/down direction. 将矩阵上下翻转, 
    类似还有左右翻转 fliplr, rot90, flipdim.
    flipud(X) returns X with columns preserved and rows flipped
    in the up/down direction.  For example,
    X = 1 4      becomes  3 6
        2 5                       2 5
        3 6                       1 4
23 pinv(A) 及inv(A) 求矩阵A 的逆矩阵
  
C、Plotting data
24 t = [0.1 : 0.01 : 0.98]
    y = sin(t)
    plot(t, y) 画正弦曲线
25 hold on; 保留当前曲线,画下一条曲线
26 xlabel 标定x轴说明
27 legend('sin','cos') 添加图例
28 title('my plot') 添加图片标题
29  print -dpng 'myPlot.png' 保存图片
30 线条颜色标注控制
   b     blue          .     point              -     solid
   g     green         o     circle             :     dotted
    r     red           x     x-mark             -.    dashdot 
    c     cyan          +     plus               --    dashed   
    m     magenta       *     star             (none)  no line
     y     yellow        s     square
     k     black         d     diamond
     w     white         v     triangle (down)
                               ^     triangle (up)
                               <     triangle (left)
                               >     triangle (right)
                               p     pentagram
                               h     hexagram
31 subplot 画子图,即将多个图合成一个图
>> subplot(1,2,1) % Divides plot a 1X2 grid, access the 1st element
>> plot(t,y1)
>> subplot(1,2,2)
>> plot(t,y2)
32 grid 加上网格
33 figure(1)
>> plot(t, y1)
>> figure(2)
>> plot(t,y2)
将y1与y2的曲线画到文件名为figure1和figure2的两个文件中
34 axis([0.5 1 -1 1]) 设定x轴范围为0.5~1,y轴范围为-1~1
35 clf Clear current figure.
36  imagesc(A)
imagesc Scale data and display as image.
把矩阵A画成彩色小方格
37  imagesc(A), colorbar, colormap gray;
colorbar 显示颜色渐变条,表明颜色含义
colormap 设置colormap性质  即RGB三色
 A color map matrix may have any number of rows, but it must have
    exactly 3 columns.  Each row is interpreted as a color, with the
    first element specifying the intensity of red light, the second
    green, and the third blue.  Color intensity can be specified on the
    interval 0.0 to 1.0.
38  a = 1; b = 2; c=3; 不会打出a b c的值
      a = 1, b = 2, c=3  会打出a b c 的值


D、Control statements: for, while, if statements
39 for 循环
 for i = 1:10,
     v(i) = 2 ^i;
   end;
>> v

v =

           2
           4
           8
          16
          32
          64
         128
         256
         512
        1024
>> indices = 1:10
 for i = indices,
      disp(i)
   end;

40 while 循环
>> while i <= 5,
     v(i) = 100;
     i = i+1;
   end;
>> v

v =

         100
         100
         100
         100
         100
          64
         128
         256
         512
        1024

>> i = 1;
>>  while true,
     v(i) = 999;
     i = i + 1;
     if i == 6,
         break;
      end;
     end;
>> exit


v =

         999
         999
         999
         999
         999
          64
         128
         256
         512
        1024
41 if elseif 判断分支语句
 v(1)=2

v =

           2
         999
         999
         999
         999
          64
         128
         256
         512
        1024

>> 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;
The value is two

42  函数的定义和使用
定义函数  squareThisNumber.m文件
function y = squareThisNumber(x)
 
y = x^2;
调用
 squareThisNumber(5)

ans =

    25
43 addpath 增加matlab搜索函数的路径
44 matlab里面定义的函数可以返回多于一个值, 这是其与C C++等编程语言
    的不同之处,C\C++里面的函数有唯一返回值
    可以允许多个返回值可以带来编程上的方便
   function [a,b] = squareAndCubeThisNumber(x)
 
a = x^2;
b = x^3;
调用
>> [x1,x2] = squareAndCubeThisNumber(5)

x1 =

    25


x2 =

   125

45 cost function J 函数示例

function J = costFunctionJ(X, y, theta)
 
% X is the "design matrix" containing our training examples.
% Y is the class labels
 
m  = size(X,1); % number of training examples
predictions = X*theta; % predictions of hypothesis on all m examples
sqrErrors = (predictions - y).^2; % squared errors
J = 1/(2*m) * sum(sqrErrors);

调用
X = [1 1; 1 2; 1 3];
y = [1; 2; 3];
theta = [0;1];

>> j = costFunctionJ(X, y, theta)

j =

     0
% squared errors is 0 in this example
>> theta = [0;0]

theta =

     0
     0

>> j = costFunctionJ(X, y, theta)

j =

    2.3333
% squared errors is 2.3333 in this example
% which is (1^2 + 2^2 + 3^2) / (2 * 3) = 2.3333

E、Vectorization
Matlab中“向量化”的实现算法,可以减少不必要的循环,对向量所有值的计算
操作一致,这是更快速更高效的算法实现思路,要注意体会matlab中“向量化”
“矩阵化”操作变量实现算法与其他编程语言Java , C, C++的不同





    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多