美文网首页
MATLAB Tricks (Updating)

MATLAB Tricks (Updating)

作者: SilentSummer | 来源:发表于2017-12-24 02:47 被阅读13次

Memo for MATLAB Tricks.

T1. Read images by for-loop

num_img = 10;    % number of images in each folder
num_fdr = 40;    % number of folders
num_ft = 50;     % number of features
sizer = 40;      % standard row size of resized image
sizec = 40;      % standard column size of resized image

filepathsrc = 'A/B';   % file path source
for i=1:num_fdr
  folderpathsrc = sprintf('%s%d',filepathsrc,i);
  for j=1:num_img
      % input the jth image in ith folder
      filename=sprintf('%s%s%d%s',folderpathsrc,'/',j,'.pgm');      
      % resize original images
      img = imresize(imread(filename), [sizer sizec], 'bilinear');  
      % input data into workspace
      eval([sprintf('%s%d%s%d','f',i,'_',j) '=img;']);
end

T2. Execute loop iterations in parallel - Parfor

T3. roots

% determine the weight lamda
syms w
F = (1-w) * F1 + w * F2;
coef = sym2poly(det(F));
lamda = roots(coef);

T4. bsxfun

Try to substitute bsxfun for for:

C = bsxfun(fun,A,B) appliesthe element-by-element binary operation specified by the function handle fun to arrays A and B,with singleton expansion enabled.fun can be one of the following built-in functions:   
@plus Plus   
@minus Minus   
@times Array multiply   
@rdivide Right array divide   
@ldivide Left array divide   
@power Array power   
@max Binary maximum   
@min Binary minimum   
@rem Remainder after division   
@mod Modulus after division   
@atan2 Four quadrant inverse tangent   
@hypot Square root of sum of squares   
@eq Equal   
@ne Not equal   
@lt Less than   
@le Less than or equal to   
@gt Greater than   
@ge Greater than or equal to   
@and Element-wise logical AND   
@or Element-wise logical OR   
@xor Logical exclusive OR

Miscellaneous

M1. Matlab Tricks

  1. 定位矩阵的全零行:find(sum(abs(A),2)==0)
  2. 结果保存到文本中:save result.txt p -ascii
  3. 把矩阵中的某些元素值为a的全部替换为b: C(C==a)=b
  4. 无界面情况下如何绘图并保存:set(gca, ‘UserData’, {‘gscatter’ x y g}); saveas(gca, ['D:/test.fig'])
  5. 在程序开头加上rand(‘state’,1); randn(‘state’,1); 以保证每次生成的随机数一致。

M2. Matlab下大矩阵运算

  • 内存
    • memory: 查看系统当前内存使用情况
    • whos: 查看每个变量所占用的内存
  • 速度
    • tic, toc: 记录每段代码的执行时间。
    • profile: 查看每条语句的详细运行情况。先运行profile on,再运行需要测试的代码,然后使用profile viewer来查看报告。
  • sparse
    • 当一个矩阵中有大量的0时就一定要采用sparse型进行运算,不只大大减少内存会消耗,而且时间消耗也会大大减少。
    • 注意,一般Sparse矩阵运算如sum, diag等之后还是sparse矩阵,而当sparse矩阵和full矩阵一起参加运算时,结果会被强制转为full矩阵。
    • Sparse矩阵在指定下标的循环运算中不占优势。
    • 注意,当一个矩阵并不是很稀疏时尽量不要采用sparse方式存储,不便于矩阵运算,对于一些矩阵操作,如求矩阵转置等操作会变得异常异常的慢!

相关文章

网友评论

      本文标题:MATLAB Tricks (Updating)

      本文链接:https://www.haomeiwen.com/subject/tuycgxtx.html