2016年5月23日 星期一

[Octave] Octave matrix slice

CASE1:

a=[1, 2, 33;4 ,5, 6; 7 ,8, 66];

a =

    1    2   33
    4    5    6
    7    8   66

a(3)       # result is a scalar
 ans =  7


a(1:4)     # show range form index 1 to(:) index 4, and result is a row vector
ans =

   1   4   7   2

a([1; 9])  # show range form index 1 and index 9 result is a column vector
ans =

    1
   66

a(1, [1, 3])  # row 1, columns 1 and 3
ans =

    1   33


a(3, 1:3)     # row 3, columns in range 1-2
ans =

    7    8   66

a(1, :)       # row 1, all columns , use really often !!!

ans =

    1    2   33


Case2:

a = [1, 2, 3, 4]
a =

   1   2   3   4

a(1:end/2)        # first half of a => [1, 2],end is the last element in the matrix
ans =

   1   2


a(end + 1) =5   # append element
 a =

   1   2   3   4   5

a(end) = []      # delete element
a =

   1   2   3   4

a(1:2:end)        # odd elements of a => [1, 3]
ans =

   1   3

a(2:2:end)        # even elements of a => [2, 4]
ans =

   2   4

a(end:-1:1)       # reversal of a => [4, 3, 2 , 1]
ans =

   4   3   2   1



 CASE3: often use in machine learning cost function

a=[1, 2, 33;4 ,5, 6; 7 ,8, 66];

a =

    1    2   33
    4    5    6
    7    8   66

[99 ; a(1,:)']

 ans =

   99
    1
    2
   33


num_labels=4;
zeros(num_labels,1)

ans =

   0
   0
   0
   0


a=[1, 2, 33;4 ,5, 6; 7 ,8, 66;55 ,476, 22]
a =

     1     2    33
     4     5     6
     7     8    66
    55   476    22

a(:,2:end) #from second column  to end

ans =

     2    33
     5     6
     8    66
   476    22

a(1,:) #get first row
ans =

    1    2   33

a(2:end) # start from element 2 to end

ans =

     4     7    55     2     5     8   476    33     6    66    22

a(:) # unroll every element


ans =

     1
     4
     7
    55
     2
     5
     8
   476
    33
     6
    66




沒有留言:

張貼留言