MATLAB Answers


improve efficiency of a matlab code that includes for loop and if statement

Asked by Locks
on 22 Apr 2013

I have the followig script which I am running for a matrix that consists of several thousand rows and which makes the full ccode very slow. Is there any way to improve the speed of the code?

Here you find the code which is saved in a seperate script and which is called by the function run the speciific script:

     dataset(:,1:9)=data9;for i=1:length(dataset(:,1))
   if dataset(i,3)==1
         vola(i)=blkimpv(dataset(i,1),dataset(i,2),dataset(i,7),dataset(i,5),dataset(i,4));   elseif dataset(i,3)==2

Which improvements are there to get the code execution the desired functions much faster?



No products are associated with this question.

1 Answer

Answer by Cedric Wannaz
on 22 Apr 2013
Edited by Cedric Wannaz
on 22 Apr 2013
 Accepted answer

It really depends whether BLKIMPV can work on vectors. If so, you can go for something like:

 dataset = zeros(size(data9,1), 9) ;
 dataset(:,1:9) = data9;
 vola = zeros(size(dataset,1), 1) ;
 id = dataset(i,3) == 1 ;
 vola(id) = blkimpv(dataset(id,1), dataset(id,2), dataset(id,7), ...
                    dataset(id,5), dataset(id,4)) ;
 id = dataset(i,3) == 2 ;
 vola(id) = blkimpv(dataset(id,1), dataset(id,2), dataset(id,7), ...
                    dataset(id,5), dataset(id,4), 10, [], {'Put'}) ;

where you might have to replace 10 and {'Put'} with arrays of these values.

I don't have the Financial Toolbox though, so I can't test.


You can read very carefully its doc and see if it takes extra params that could be used to better select how your data is processed (eliminate operations, etc), but other than that, I don't think that there is much that you can do except using another function (changing the approach), or rewritting it specifically for what you need.

on 23 Apr 2013

ok, I will try that. thanks for your help!

You're welcome! Try to use the profiler on a regular basis in the beginning (even when you don't really need to); it will give you a lot of insights into your code.

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!