1. 程式人生 > >matlab實戰中一些重要的函式總結

matlab實戰中一些重要的函式總結

這段時間看了一些大型的matlab工程檔案(如:faster r-cnn),對於工程中經常要用到的一些函式進行一個總結。
1、路徑問題。
這主要涵括檔案路徑的包含和組合。

curdir = fileparts(mfilename('fullpath'));
addpath(genpath(fullfile(curdir, 'utils')));
mkdir_if_missing(fullfile(curdir, 'utils'));
caffe_path = fullfile(curdir, 'external', 'caffe', 'matlab');
if exist(caffe_path, 'dir'
) == 0 error('matcaffe is missing from external/caffe/matlab; See README.md'); end

我們經常需要引用不同資料夾下的檔案或是函式。
mfilename 表示正在執行的函式的路徑
fileparts 則返回檔案上層的資料夾路徑
fullfile 則返回組合檔案的全路徑
genpath 遞迴的產生該資料夾下的所有檔案的路徑
addpath 路徑加入到函式或檔案搜尋的範圍內
exist 檢視路徑是否存在
mkdir_if_missing 如果不存在就建立對應的資料夾

dirpath = '/home/Deeplearning'
; filepath = [dirpath, '/%s.txt']; for i=1:10 filepath_real = sprintf(filepath, num2str(i)); end

這時路徑組合中經常出現的情況
用[]拼接通用路徑,具體情況時再加入需要改動的部分,需改動的部分在拼接通用路徑時預留
2、查詢和排序

[B,I] = sort(A,mode,dim)

A為輸入矩陣或向量,mode為排序的模式,升序還是降序,dim表示按第幾維進行排序;B為排序後的矩陣或向量,I為排序後的各元素的序號。

X = [3 2 0; -5 0 7; 0 0 1]
[row,col,v] = find(X>1)

X>1為條件,即矩陣X中元素大小比1大的元素,row,col, v分別為返回的元素的位置橫、縱座標、元素本身。
3、隨機過程與函式
randi ,random等
4、維度轉換

A = [1 2; 3 4]; permute(A,[2 1])
ans =
     1     3
     2     4

squeeze移除掉多餘的某一緯度

Create a 2-by-1-by-3 array and remove the singleton column dimension to form a 2-by-3 matrix.
y = rand(2,1,3)
z = squeeze(y)
y(:,:,1) =
    0.8147
    0.9058
y(:,:,2) =
    0.1270
    0.9134
y(:,:,3) =

    0.6324
    0.0975
z =

    0.8147    0.1270    0.6324
    0.9058    0.9134    0.0975

5、畫圖
plot , subplot, figure, meshgrid等
對於如何在一幅圖片中的指定位置加入文字和標註可參考我的上一篇博文http://blog.csdn.net/sunnyxiaohu/article/details/51150430
中 function showboxes(im, boxes, legends, color_conf)的解析。
6、資料的轉換
round:
Round to nearest decimal or intege
這個在處理資料時很有用
cell2mat:
num2str, str2num
cat(1,some_cell);
unique();
這些函式在進行各種格式之間的資料轉換用的很多,可以自行查閱文件。
matlab中經常強調向量化程式設計,這樣能加快執行的速度。那麼對於array或者cell,我們怎樣儘量的少使用for迴圈而用向量化程式設計呢?

A = randi(10,4,2)%假設你有4組資料,每一組資料有2維,你需要對每組資料進行某個處理

     7     7
     8     2
     8     8
     4     1
A_cell = num2cell(A,2)%先將其按行轉化為cell

    [1x2 double]
    [1x2 double]
    [1x2 double]
    [1x2 double] 
y_hat = cellfun(@(x) (x.*10) ,A_cell, 'UniformOutput', false)%這樣就可用cellfun進行向量化處理了
    [1x2 double]
    [1x2 double]
    [1x2 double]
    [1x2 double]
%處理完成之後,又變換回原來的格式
y = cat(1,y_hat{:})
    70    70
    80    20
    80    80
    40    10

7、文件的讀寫
這裡主要講三種

[gtids,t]=textread(sprintf(VOCopts.imgsetpath,VOCopts.testset),'%s %d');

[A,B,C,...] = textread(filename,format)
[A,B,C,...] = textread(filename,format,N)
[...] = textread(...,param,value,...)

對於txt檔案的讀取,用textread基本就已經夠用了,這裡面有很多個引數可選,自己琢磨一下。

對於圖片的讀取,用imread()即可,更具體的在圖片上進行操作可參考我的上一篇博文中的showbox()
圖片的儲存主要講解這兩種:

1、print(gcf,'-djpeg',filename,);
2、saveas(gcf,filename,filetype);

對於xml檔案的讀取:

xmlwrite()xmlread()
這裡有一個文件可供參考,講得很詳細。

%% Tutorial for xml_io_tools Package
% By Jarek Tuszynski
%
% Package xml_io_tools can read XML files into MATLAB struct and writes
% MATLAB data types to XML files with help of simple interface to
% MATLAB’s xmlwrite and xmlread functions.
%
% Two function to simplify reading and writing XML files from MATLAB:
%
% * Function xml_read first calls MATLAB’s xmlread function and than
% converts its output (‘Document Object Model’ tree of Java objects)
% to tree of MATLAB struct’s. The output is in the format of nested
% structs and cells. In the output data structure field names are based on
% XML tags.
%
% * Function xml_write first convert input tree of MATLAB structs and cells
% and other types to tree of ‘Document Object Model’ nodes, and then writes
% resulting object to XML file using MATLAB’s xmlwrite function. .
%
%% This package can:
% * Read most XML files, created inside and outside of MATLAB environment,
% and convert them to MATLAB data structures.
% * Write any MATLAB’s struct tree to XML file
% * Handle XML attributes and special XML nodes like comments, processing
% instructions and CDATA sections
% * Supports base64 encoding and decoding to allow handling embeded binary
% data
% * Be studied, modified, customized, rewritten and used in other packages
% without any limitations. All code is included and documented. Software
% is distributed under BSD Licence (included).
%
%% This package does not:
% * Guarantee to recover the same Matlab objects that were saved. If you
% need to be able to recover carbon copy of the structure that was saved
% than you will have to use one of the packages that uses special set of
% tags saved as xml attributes that help to guide the parsing of XML code.
% This package does not use those tags.
% * Guarantee to work with older versions of MATLAB. Functions do not work
% with versions of MATLAB prior to 7.1 (26-Jul-2005).
%
%% Change History
% * 2006-11-06 - original version
% * 2006-11-26 - corrected xml_write to handle writing Matlab’s column
% arrays to xml files. Bug discovered and diagnosed by Kalyan Dutta.
% * 2006-11-28 - made changes to handle special node types like:
% COMMENTS and CDATA sections
% * 2007-03-12 - Writing CDATA sections still did not worked. The problem
% was diagnosed and fixed by Alberto Amaro. The fix involved rewriting
% xmlwrite to use Apache Xerces java files directly instead of MATLAB’s
% XMLUtils java class.
% * 2007-06-21 - Fixed problem reported by Anna Kelbert in Reviews about
% not writing attributes of ROOT node. Also: added support for Processing
% Instructions, added support for global text nodes: Processing
% Instructions and comments, allowed writing tag names with special
% characters
% * 2007-07-20 - Added tutorial script file. Extended support for global
% text nodes. Added more Preference fields.
% * 2008-01-23 - Fixed problem reported by Anna Krewet of converting dates
% in format ‘2007-01-01’ to numbers. Improved and added warning messages.
% Added detection of old Matlab versions incompatible with the library.
% Expanded documentation.
% * 2008-06-23 - Fixed problem with writing 1D array reported by Mark Neil.
% Extended xml_read’s Pref.Num2Str to 3 settings (never, smart and always)
% for better control. Added parameter Pref.KeepNS for keeping or ignoring
% namespace data when reading. Fixed a bug related to writing 2D cell
% arrays brought up by Andrej’s Mosat review.
% * 2008-09-11 - Resubmitting last upload - zip file is still old
% * 2009-02-26 - Small changes. More error handling. More robust in case of
% large binary objects. Added support for Base64 encoding/decoding of
% binary objects (using functions by Peter J. Acklam).
% * 2009-06-26 - changes to xml_read: added CellItem parameter to allow
% better control of reading files with ‘item’ notation (see comment by
% Shlomi); changed try-catch statements so xml_read would work for mablab
% versions prior to 7.5 (see Thomas Pilutti comment)
% * 2009-12-03 - added PreserveSpace parameter for contolling empty string
% handling as suggested by Sebastiaan. Fix suggested by Michael Murphy.
% Fixed number recognition code as suggested by Yuan Ren.
% * 2010-05-04 - implemented fixes suggested by Dylan Reynolds from Airbus.
% * 2010-07-28 - implemented support for 2D arrays of cells and structs
% suggested by Rodney Behn from MIT Lincoln Laboratory. Also attempted
% large scale cleanup of xml_write function
% * 2010-08-18 - minor extension to allow better handling of logical
% scalars and arrays and function handles suggested by Andreas Richter
% and others
% * 2010-09-20 - allow reading and writing of sparse matrices. Improve
% reading of 1D boolean arrays.
% * 2010-11-05 - Fix problem with empty cells reported by Richard Cotton;
% fixed issues with reading boolean arrays reported by Zohar Bar-Yehuda;
% Improved speed of base64 coding and decoding by switching to java based
% code.
%% Licence
% The package is distributed under BSD License
format compact; % viewing preference
clear variables;
type(‘license.txt’)

%% Write XML file based on a Struct using “xml_write”
% Any MATLAB data struct can be saved to XML file.
MyTree=[];
MyTree.MyNumber = 13;
MyTree.MyString = ‘Hello World’;
xml_write(‘test.xml’, MyTree);
type(‘test.xml’)

%% Read XML file producing a Struct using “xml_read”
[tree treeName] = xml_read (‘test.xml’);
disp([treeName{1} ’ =’])
gen_object_display(tree)

%% “Pref.XmlEngine” flag in “xml_write”
% Occasionaly some operations are performed better by Apache Xerces XML
% engine than default xmlread function. That is why xml_write provide an
% option for choosing the underlaying xml engine. Code below performs the
% same operation as the previous section but using Apache Xerces XML engine.
% Notice that in this case name of root element
% was passed as variable and not extracted from the variable name.
% Pref=[]; Pref.XmlEngine = ‘Xerces’; % use Xerces xml generator directly
% xml_write(‘test.xml’, MyTree, ‘TreeOfMine’, Pref);
% type(‘test.xml’)
%
% %% Writing Struct with different type MATLAB arrays
% MyTree=[];
% MyTree.Empty = []; % Empty variable
% MyTree.Num_1x1 = 13; % simple scalar
% MyTree.Vec_1x3 = [1 2 3]; % horizontal vector
% MyTree.Vec_4x1 = [1; 2; 3; 4]; % vertical vector
% MyTree.Mat_2x2 = [1, 2; 3, 4]; % 2D matrix
% MyTree.Cube_3D = reshape(1:8,[2 2 2]); % 3D array
% MyTree.String1 = ‘[2003 10 30]’; % number string with [] brackets
% MyTree.String2 = ’ 2003 10 30 ‘; % number string without [] brackets
% MyTree.Logical_1x1 = false; % single logical
% MyTree.Logical_2x2 = [false, true; true, false]; % 2D matrix of logicals
% MyTree.Logical_Str = ‘False False True True’;
% MyTree.Int_2x2 = uint8([1 2;3 4]); % 2D matrix of uint8 integers
% MyTree.Complex_1x1 = complex(1, 7); % complex scalar
% MyTree.Complex_2x2 = complex([1 2;3 4],[2 2;7 7]); % 2D matrix of complex numbers
% MyTree.Sparse_9x9 = sparse(1:9,1:9,1); % sparse 9x9 matrix
% MyTree.Function = @sum; % function handle
% xml_write(‘test.xml’, MyTree);
% type(‘test.xml’)
%
% %% Read Struct with MATLAB arrays
% % Notice that ‘Cube_3D’ did not preserve original dimentions
% [tree treeName] = xml_read (‘test.xml’);
% disp([treeName{1} ’ =’])
% gen_object_display(tree)
%
% %% “Pref.StructItem” flag in “xml_write” (controls 1D arrays of structs)
% % Create a simple structure with 1D array of struct’s
MyTree = [];
MyTree.a(1).b = ‘jack’;
MyTree.a(2).b = ‘john’;
gen_object_display(MyTree)
%%
% *Write XML with “StructItem = true” (default). Notice single ‘a’
% section and multiple ‘item’ sub-sections. Those subsections are used
% to store array elements*
wPref.StructItem = true;
xml_write(‘test.xml’, MyTree, ‘MyTree’,wPref);
type(‘test.xml’)
fprintf(‘\nxml_read output:\n’)
gen_object_display(xml_read (‘test.xml’))
%%
% Write XML with “StructItem = false”. Notice multiple ‘a’ sections
wPref.StructItem = false;
xml_write(‘test.xml’, MyTree, ‘MyTree’,wPref);
type(‘test.xml’)
fprintf(‘\nxml_read output:\n’)
gen_object_display(xml_read (‘test.xml’))
%%
% Notice that xml_read function produced the same struct when reading both files
%%
% Potential problems with “StructItem = true”:
wPref.StructItem = true;
MyTree1 = []; MyTree1.a.b = ‘jack’;
MyTree2 = []; MyTree2.a(1).b = ‘jack’;
MyTree3 = []; MyTree3.a(2).b = ‘jack’;
xml_write(‘test.xml’, MyTree1, [], wPref); type(‘test.xml’);
xml_write(‘test.xml’, MyTree2, [], wPref); type(‘test.xml’);
xml_write(‘test.xml’, MyTree3, [], wPref); type(‘test.xml’);
%%
% *Notice that MyTree1 and MyTree2 produce identical files with no ‘items’,
% while MyTree2 and MyTree3 produce very different file structures. It was
% pointed out to me that files produced from MyTree2 and MyTree3 can not
% belong to the same schema, which can be a problem. The solution is to use
% cells.*
wPref.CellItem = true;
wPref.NoCells = true;
MyTree2 = []; MyTree2.a{1}.b = ‘jack’;
MyTree3 = []; MyTree3.a{2}.b = ‘jack’;
xml_write(‘test.xml’, MyTree2, [], wPref); type(‘test.xml’);
xml_write(‘test.xml’, MyTree3, [], wPref); type(‘test.xml’);

%% “Pref.CellItem” flag in “xml_write” (controls 1D arrays of cells)
% Create a simple structure with cell arrays
MyTree = [];
MyTree.a = {‘jack’, ‘john’};
disp(MyTree)
%%
% *Write XML with “CellItem = true” (default). Notice single ‘a’
% section and multiple ‘item’ sections*
Pref=[]; Pref.CellItem = true;
xml_write(‘test.xml’, MyTree, ‘MyTree’,Pref);
type(‘test.xml’)
fprintf(‘\nxml_read output:\n’);
disp(xml_read (‘test.xml’))
%%
% Write XML with “CellItem = false”. Notice multiple ‘a’ sections
Pref=[]; Pref.CellItem = false;
xml_write(‘test.xml’, MyTree, ‘MyTree’,Pref);
type(‘test.xml’)
fprintf(‘\nxml_read output:\n’);
disp(xml_read (‘test.xml’))
%%
% Notice that xml_read function produced the same struct when reading both files

%% “Pref.NoCells” flag in “xml_read”
% Create a cell/struct mixture object
MyTree = [];
MyTree.a{1}.b = ‘jack’;
MyTree.a{2}.b = [];
MyTree.a{2}.c = ‘john’;
gen_object_display(MyTree);
%%
% Save it to xml file
Pref=[]; Pref.CellItem = false;
xml_write(‘test.xml’, MyTree, ‘MyTree’,Pref);
type(‘test.xml’)
%%
% Read above file with “Pref.NoCells=true” (default) - output is quite different then input
% By default program is trying to convert everything to struct’s and arrays
% of structs. In case arrays of structs all the structs in array need to have the
% same fields, and if they are not than MATLAB creates empty fields.
Pref=[]; Pref.NoCells=true;
gen_object_display(xml_read(‘test.xml’, Pref))
%%
% Read above file with “Pref.NoCells=false” - now input and output are the same
% Cell arrays of structs allow structs in array to have different fields.
Pref=[]; Pref.NoCells=false;
gen_object_display(xml_read(‘test.xml’, Pref))

%% “Pref.ItemName” flag in “xml_write” (customize 1D arrays of structs and cells)
% Create a cell/struct mixture object
MyTree = [];
MyTree.a{1}.b = ‘jack’;
MyTree.a{2}.c = ‘john’;
gen_object_display(MyTree);
%%
% Save it to xml file, using ‘item’ notation but with different name
Pref=[];
Pref.CellItem = true;
Pref.ItemName = ‘MyItem’;
xml_write(‘test.xml’, MyTree, ‘MyTree’,Pref);
type(‘test.xml’)

%% “Pref.ItemName” flag in “xml_read”
% Read above file with default settings (“Pref.ItemName = ‘item’”)
% The results do not match the original structure
Pref=[]; Pref.NoCells = false;
gen_object_display(xml_read(‘test.xml’, Pref))
%%
% *Read above file with “Pref.ItemName = ‘MyItem’” - now saved and read
% MATLAB structures are the same*
Pref=[];
Pref.ItemName = ‘MyItem’;
Pref.NoCells = false;
gen_object_display(xml_read(‘test.xml’, Pref))

%% “Pref.CellItem” flag in “xml_read”
% “Pref.ItemName” is used to create xml files with clearly marked arrays
% “Pref.CellItem” flag in “xml_read” ensures that they are always read as
% arrays by forcing output to stay in cell format. In cell format s{1} is
% different than s, while s(1) is indistinguishable from s.
%%
% Create a test file
MyTree = [];
MyTree.a1{1}.b = ‘jack’; % a1 - single struct
MyTree.a2{1}.b = ‘jack’; % a2 - cell array of structs with the same fields
MyTree.a2{2}.b = ‘john’;
MyTree.a3{1}.b = ‘jack’; % a3 - cell array of structs with the different fields
MyTree.a3{2}.c = ‘john’;
Pref=[];
Pref.CellItem = true;
Pref.Debug = true;
xml_write(‘test.xml’, MyTree, ‘MyTree’,Pref);
type(‘test.xml’)
%%
% Read above file with “Pref.CellItem = true” (default)
% All outputs are in cell format
Pref=[];
Pref.NoCells = false; % allow cell output
Pref.CellItem = true; % keep ‘item’ arrays as cells
gen_object_display(xml_read(‘test.xml’, Pref))
%%
% Read above file with “Pref.CellItem = false”
% Outputs format is determined by content
Pref=[];
Pref.NoCells = false; % allow cell output
Pref.CellItem = false; % allow ‘item’ arrays to beheave like other fields
gen_object_display(xml_read(‘test.xml’, Pref))
%%
% Read above file with “Pref.CellItem = false” and “Pref.NoCells = true”
% All outputs are in struct format
Pref=[];
Pref.NoCells = true; % don’t allow cell output
Pref.CellItem = false; % allow ‘item’ arrays to beheave like other fields
gen_object_display(xml_read(‘test.xml’, Pref))

%% “Pref.CellTable” flag in “xml_write” (controls 2D arrays of cells)
% Create a structure with 2D arrays of cells
MyTree = [];
MyTree.M = {[1,2;3,4], ‘M12’; struct(‘a’,’jack’), {11, ‘N12’; 21, ‘N22’}};
gen_object_display(MyTree)
%%
% *Write XML with “CellTable = ‘Html” (default). This option mimics use of
% HTML “tr” and “td” tags to encode 2D tables. Tag names can
% be changed using TableName parameter (see below)*
wPref = [];
wPref.CellTable = ‘Html’;
xml_write(‘test.xml’, MyTree, ‘MyTree’,wPref);
type(‘test.xml’)
fprintf(‘\nxml_read output:\n’)
rPref=[]; rPref.NoCells=false;
gen_object_display(xml_read(‘test.xml’, rPref))
%%
% Write XML with “CellTable = ‘Vector’”.
% Converts 2D arrays to 1D array and item or regular notation. This option
% is mostly provided for backward compatibility since this was the
% behavior in prior verions of the code
wPref = [];
wPref.CellTable = ‘Vector’;
xml_write(‘test.xml’, MyTree, ‘MyTree’,wPref);
type(‘test.xml’)
fprintf(‘\nxml_read output:\n’)
rPref=[]; rPref.NoCells=false;
gen_object_display(xml_read(‘test.xml’, rPref))
%%
% Create a simpler structure without struct’s
MyTree = [];
MyTree.M = {[1,2;3,4], ‘M12’; ‘M21’, {11, ‘N12’; 21, ‘N22’}};
gen_object_display(MyTree)
%%
% *Write XML with “CellTable = ‘Matlab”. This option encodes tables
% consisting of numbers, strings and other cell arrays as MATLAB command
% string. Unlike ‘Html’ option it does not work if one of the cells is
% a struct*
wPref = [];
wPref.CellTable = ‘Matlab’;
xml_write(‘test.xml’, MyTree, ‘MyTree’,wPref);
type(‘test.xml’)
fprintf(‘\nxml_read output:\n’)
rPref=[]; rPref.NoCells=false;
gen_object_display(xml_read(‘test.xml’, rPref))

%% Write 2D cell array in HTML format
MyTree = [];
MyTree.table.ATTRIBUTE.border=1;
MyTree.table.CONTENT = {‘Apples’, ‘44%’; ‘Bannanas’, ‘23%’; ‘Oranges’, ‘13%’; ‘Other’, ‘10%’};
xml_write(‘html/test.html’, MyTree);
type(‘html/test.html’)
%%
% Click on