User Tools

Site Tools


public:matlab_tips

This is an old revision of the document!


Matlab Tips

General tips

  1. 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

disp('     ');
for i = 1:x
    fprintf('\b\b\b\b\b\b%05.2f%%', i/x*100);
    %%%%% Do your biddings here %%%%%
end
disp(' ');

Highly unscientific benchmark of prod()

Sparse vs Dense

>> 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.
>> 

Prod vs repeated multiplication

Script

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;

Results

>> test
Elapsed time is 0.168450 seconds.
Elapsed time is 1.003991 seconds.

Note that with repeated multiplication your numerical accuracy will suffer too!

public/matlab_tips.1459781435.txt.gz · Last modified: 2018/03/31 00:38 (external edit)