Reputation: 79
I have no experience with MATLAB before. Now, I am trying to edit a MATLAB program to make it runnable in GNU Octave (both on Windows system).
I fixed some errors such as +:nonconformant arguments (op1 is 1x1, op2 is 0x1) by changing some operators or special characters. For example, I changed
val = textscan(unit53,'%d %s %f %f %f %f \r\n');
to
val = textscan(unit53,'%d %s %f %f %f %f "\r""\n"');
I successfully edited the program and it runs without an error. However, my edited program takes about 32 hours to finish running. The original MATLAB program only takes about 10 minutes to run.
The slow part of program is a for loop about declaration, filling matrices with the information read from a document, and doing calculation with those matrices.
Does this happen (runs slower) every time when you try to run MATLAB code in Octave?
How to make that MATLAB code run faster?
Upvotes: 0
Views: 948
Reputation: 13081
The original MATLAB codes only takes about 10 minutes to run. The slow part of program is a for loop about declaration , filling matrix with the information read from a document,and doing calculation with those matrix.
As a rule of thumb, if you see a for loop with many iterations in an Octave program, that won't be a good program. Matlab used to be the same but now they have a decent JIT that speeds up such sloppy code. If your code is vectorized, then you shouldn't see that much of a difference between Octave and Matlab.
How to do it, depends on your problem. Many functions will actually work fine with arrays it's just that people don't use them that way. Go into your for loop, and take each line outside of the loop, one by one. Depending on your problem, it might not be easy. An alternative, if the loop iterations are independent from each other, consider using the parallel package.
As an example, I once had a program that in Matlab ran in ~20 minutes. In Octave, I killed it after 2 days. The main issue were in two for loops, one of them was iterating over each pixel of a 512*512*2000 image. After I vectorized, Octave ran it in under 2 minutes. I have had to port many Matlab programs, this is very common.
Edit (answer to comment): there are plenty of examples and tutorials out there about vectorization but there's no silver bullet. The solution is often unique and it will be dependent on your code. For the specific case of the difference between continuous elements, you should use diff
to get an array of the differences and then work on it. Vectorizing your code will look like an increase in memory usage but it will be much faster.
Upvotes: 2