User Tools

Site Tools


public:matlab_tips

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revisionBoth sides next revision
public:matlab_tips [2016/04/04 14:44] – [Sparse vs Dense] fangfufupublic:matlab_tips [2016/04/04 14:50] – old revision restored (2016/04/02 07:41) fangfufu
Line 1: Line 1:
 +====== Matlab Tips ======
 +===== General tips =====
 +  - If you plan to use parallel for-loop, put the parfor statement in the outermost loop to reduce inter-process communication.
 +===== Simple text progress bar =====
 +<code matlab>
 +disp('     ');
 +for i = 1:x
 +    fprintf('\b\b\b\b\b\b%05.2f%%', i/x*100);
 +    %%%%% Do your biddings here %%%%%
 +end
 +disp(' ');
 +</code>
  
 +===== Highly unscientific benchmark of prod() =====
 +==== Sparse vs Dense ====
 +<code matlab>
 +>> a = rand(1000);
 +>> b = eye(1000);
 +>> c = sparse(a);
 +>> d = sparse(b);
 +>> tic; for i = 1:10000; prod(a); end; toc
 +Elapsed time is 7.212577 seconds.
 +>> tic; for i = 1:10000; prod(b); end; toc
 +Elapsed time is 3.566560 seconds.
 +>> tic; for i = 1:10000; prod(c); end; toc
 +Elapsed time is 27.455137 seconds.
 +>> tic; for i = 1:10000; prod(d); end; toc
 +Elapsed time is 0.030041 seconds.
 +>> tic; for i = 1:10000; prod(a); end; toc
 +Elapsed time is 7.250969 seconds.
 +>> tic; for i = 1:10000; prod(b); end; toc
 +Elapsed time is 3.645549 seconds.
 +>> tic; for i = 1:10000; prod(c); end; toc
 +Elapsed time is 27.538796 seconds.
 +>> tic; for i = 1:10000; prod(d); end; toc
 +Elapsed time is 0.029214 seconds.
 +>>
 +
 +>> n = 100000;
 +>> a = rand(n,1);
 +>> b = 1;
 +>> tic; for i = 1:n; prod(a); end; toc;
 +Elapsed time is 4.849304 seconds.
 +>> tic; for i = 1:n; b = b * prod(a(i)); end; toc
 +Elapsed time is 0.004573 seconds.
 +>> 
 +</code>
 +
 +==== Prod vs repeated multiplication ====
 +=== Script ===
 +<code matlab>
 +clear;
 +n = 10000;
 +a = rand(n,1) * exp(1);
 +b = 1;
 +
 +tic; 
 +for i = 1:n; 
 +    c = prod(a); 
 +end; 
 +toc;
 +
 +tic; 
 +for j = 1:n
 +    for i = 1:n; 
 +        b = b * a(i); 
 +    end; 
 +end
 +toc;
 +</code>
 +=== Results ===
 +<code matlab>
 +>> test
 +Elapsed time is 0.168450 seconds.
 +Elapsed time is 1.003991 seconds.
 +</code>
 +Note that with repeated multiplication your numerical accuracy will suffer too!
public/matlab_tips.txt · Last modified: 2018/03/31 00:38 by 127.0.0.1