1. 程式人生 > >matlab中dir函式以及sort函式的用法

matlab中dir函式以及sort函式的用法

dir函式的作用:返回當前路徑中的所有檔案以及資料夾所組成的列表

dir %returns a list of files and folders in the current folder.類似於Dos命令中的DIR

dir name  (或者 dir(name)) %returns a list of files and folders that match the string name;返回指定路徑name所有檔案及資料夾組成的列表;

listing = dir(name)    % returns attributes about name;返回指定路徑name屬性的結構體型別的陣列。即陣列中每一個元素以結構體型別儲存著每個子檔案的資訊。注意必須賦予變數。

>>a=dir('my_dir')

61x1 struct array with fields:
    name % 'my_dir'路徑下所有檔案的name列表
    date %對應檔案的建立日期
    bytes
    isdir
    datenum

例,我們想知道該資料夾下第三個檔案的名字,即就是訪問該結構體中的name成員

>>a(3).name

ans =  xxx.jpg  %假設是檔名為xxx.jpg

具體細節可在matalb中輸入>>doc dir 或者 help dir

sort 函式的用法

>> help sort 

sort   Sort in ascending or descending order.
    For vectors, sort(X) sorts the elements of X in ascending order.
    For matrices, sort(X) sorts each column of X in ascending order.
    For N-D arrays, sort(X) sorts along the first non-singleton
    dimension of X. When X is a cell array of strings, sort(X) sorts
    the strings in ASCII dictionary order.
 
    Y = sort(X,DIM,MODE)


    has two optional parameters.  
    DIM selects a dimension along which to sort.%指定對哪個維度進行排序
    MODE selects the direction of the sort. %指定是升序還是降序
       'ascend' results in ascending order
       'descend' results in descending order
    The result is in Y which has the same shape and type as X.%返回結果的shape和型別與輸入一致
 
    [Y,I] = sort(X,DIM,MODE) also returns an index matrix I.%返回排序後的元素值和索引值,
    If X is a vector, then Y = X(I).  
    If X is an m-by-n matrix and DIM=1, then
        for j = 1:n, Y(:,j) = X(I(:,j),j); end
 
  例>>X = [3 7 5; 0 4 2]  %2rows 3cols

     ans =  3 7 5

                 0 4 2
  >>sort(X,1) %按第1個維度排序,由於matlab是按列優先儲存,因此按列向量排序結果如下:

     ans =  0 4 2

                 3 7 5 

  >>sort(X,2)    

      ans =  3 5 7

                  0 2 4 
%%返回降序後的元素值和索引值

例 >> X=[8 4 6 2 1 5]

ans =  8     4     6     2     1     5

    >>[value, index]=sort(x,'descend')

value =  8     6     5     4     2     1

index =  1     3     6     2     4     5

具體細節可在matalb中輸入>>doc sort