MATLAB Tricks (Updating)

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方式存储,不便于矩阵运算,对于一些矩阵操作,如求矩阵转置等操作会变得异常异常的慢!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值