Trying to speed up some MATLAB code

In summary, the conversation discusses the use of MATLAB code to calculate the forward kinematics for a robotic arm. The code involves the multiplication of a series of 4x4 matrices and needs to be run frequently when changing the configuration of the arm. The person is hoping to eliminate the for loop in the code and mentions the possibility of using vectorization or sparse matrices. They also mention the Numerical Recipes website as a potential resource. Another person suggests writing a second version of the code in C for comparison. The C code is found to be significantly faster than the MATLAB code. Some potential strategies for combining the convenience of MATLAB and the speed of C are also mentioned.
  • #1
sprince09
8
0
Hi guys,

I've got some MATLAB code that calculates the forward kinematics for a robotic arm. This calculation relies on the successive multiplication of a series of 4x4 matrices, and currently I have this coded (more or less) as:

Code:
...
T(:,:, 1) = T0;
for i = 2:njoints
    T(:,:, i+1) = T(:,:, i-1) * Tlocal(:,:, i);
end
...

T0 and Tlocal are both known quantities, and their calculation is trivial in comparison to the above code. T is a series of 4x4 matrices. This code needs to be run every time I change the configuration of the robotic arm (ie, change a joint angle), so it get's evaluated very frequently in my program.

What I am hoping to do is somehow eliminate the for loop, either by vectorizing this code (which I don't think is possible) or somehow use sparse matrices to perform this calculation. I'd like to stay away from big paradigm shifts, like writing a MEX function or switching to quaternion representation, as I'm trying to keep this code as human-readable as possible.

Anyone have any suggestions?
 
Last edited:
Physics news on Phys.org
  • #2
The Numerical Recipes website has some information on this subject. I do not use MatLab on a regular basis so I am not in a good position to provide you the best help.

Also, the NR routines can be error prone and are not the most elaborate or bug free routines out there but they are relativley inexpensive and easy to implement for most run of the mill problems.

See link below.

http://www.nr.com/nr3_matlab.html

Thanks
Matt
 
  • #3
Yeah, I think I'm just going to write a 2nd copy of the code in C to do speed comparisons with. Thanks anyway
 
  • #4
If you can, let us know how "quick" the C code is compared to MatLab.

Thanks
Matt
 
  • #5
Well, I haven't written the full version of the C code, but I am curious how MATLAB (and Octave) compares to C for some simple matrix operations, especially multiplication.

My test: perform 1,000,000 4x4 matrix multiplications in both MATLAB, GNU Octave, and C and see how long each takes to multiply. For the C code, I'm using the GSL matrix library with a few wrapper functions I wrote, for MATLAB, I'm using R2009a, and for Octave, I'm using Octave 3.0.1. Test machine is an Asus EEE 1000 with 1.6 GHz processor running Ubuntu 9.04.

MATLAB/Octave code:

Code:
% MATLAB test code

A = rand(4,4);
B = rand(4,4);
C = zeros(4,4);

tic();
for i = 1:30
    for j = 1:1000000
        C = A * B;
    end
end
disp(toc()/30.0);


C Code:

Code:
// C test code
// Compile with:  
// 
// gcc -o mattest -I Programming/c/matrix/ -L Programming/c/matrix/ -lm -lgsl -lgslcblas mattest.c

#include <stdlib.h>
#include <stdio.h>
#include <matrix.h>


int main(void){
    
    // Declare vars
    int i, j;
    struct timeval t0, t1;
    double t;
    matrix_t *A, *B, *C;
    
    // Allocate matrices
    A = mat_malloc(4,4);
    B = mat_malloc(4,4);
    C = mat_malloc(4,4);
    
    // Randomize A and B
    for(i = 0; i < 4; i++){
        for(j = 0; j < 4; j++){
            mat_set(A, i, j, mat_drand_norm());
            mat_set(B, i, j, mat_drand_norm());
        }
    }
    
    // Check time
    gettimeofday(&t0, NULL);
    t = 0;
    for(i = 0; i < 30; i++){
        for(j = 0; j < 1000000; j++){
            mat_mult(A, B, C);
        }
    }
    t = mat_time_elapsed(&t0, &t1) / 30.0;
    printf("Average time elapsed: %lf seconds\n", t);
    
    // Free memory
    mat_free(A);
    mat_free(B);
    mat_free(C);
    
    return 0;
}


Results:

I ran each of the above programs and got the following results. Each program runs the
main loop 30 times then reports the average run time (I read in a book somewhere once when I was like 20 that if you conduct and experiment, it should be repeatable at least 30 times to be considered valid... completely arbitrary I know).

Octave: 37.6479 seconds per 1,000,000 4x4 multiplications

MATLAB: 9.7316 seconds

C: 1.357249 seconds


Conclusion:

C code is 10x faster than MATLAB, and Octave is much, much slower than MATLAB. Pretty much what I expected... MATLAB is good for prototyping, C is good for actual work, and Octave is a not-quite-as-good-as-MATLAB MATLAB replacement.
 
  • #6
WOW! Those times are very different.

Thanks for the information.

Matt
 
  • #7
And expected. In graduate school we wrote a 1D CFD solver. I was the only one programming in FORTRAN. Everyone else's code, which was written in Matlab tooks around 15-30 minutes to solve; mine took under a minute.
 
  • #8
Yeah, the only real reasons I do anything in MATLAB at all are that the syntax and plotting are stupid easy, even for stuff like moving 3D surfaces. If I could find a 3D plotting library for C that wasn't awful to use, I'd ditch MATLAB all together...
 
  • #9
A common strategy is to use Matlab first to prototype a model. Once the prototype is working as you want, you can then write the equivalent C code, compile it to a library, and call it from within Matlab. If you know what you're doing, you'll end up with a situation where you have all the convenience of the Matlab environment combined with the raw speed of a self-compiled C backend for your main routine.
 
  • #10
Is T completely allocated before you run the loop? If you have only assigned the first matrix in T, meaning T(:,:,1), then every time through the loop it is allocating memory for the next matrix. This can add very significantly to the matrix. It is better to do something like T = zeros(T0_rows,T0_cols,num) to have Matlab allocate all of the memory before you run the loop in that case.

Also, I'm really starting to like Python (which is free) so you might check that out. It is fairly similar to Matlab in programming style. It isn't as fast as C/C++/Fortran in general, but I think it would be faster than Matlab with something like this. If you use the Spyder IDE then it is even more like Matlab. Also, you will want to get the numpy, scipy, and matplotlib packages if you are doing Python for science- or engineering-related things. It's just something to check out if you feel like it.
 
  • #11
Yup, T is completely pre-allocated. I'd also considered writing a mex function to do this calculation, but it really isn't that important because I'm looking more at algorithm efficiency (eg, number of iterations) rather than execution time. The matrix calculation I was originally asking about is a necessary calculation for part of the algorithm, so in the interest of saving time during testing, I was looking for an alternative way to calculate T.


I had taken a look at python about 6 months ago (scipy, numpy, matplotlib, etc...) but I found 3D plotting to be kind of limited/incomplete... at least for the version that Ubuntu keeps in their repos. Which is too bad really, because python syntax is very straightforward and it's relatively easy to write python code which is much more feature-complete than MATLAB code.

I also went through a Scilab phase, which I liked, but I didn't really get much into it because MATLAB is kind of an industry standard for me, (I'm a mechanical engineer), and I don't really have a ton of time to spend learning a new language :/
 
Last edited:
  • #12
I also went through a Scilab phase ...

What did you think of Scilab? I just started using it for simple calculations.

Thanks
Matt
 
  • #13
I liked it... I'd probably use it instead of MATLAB if I didn't already know MATLAB.

I know Scilab is pretty big in China, and it's really gotten much more usable in the past few months, so I wouldn't be surprised if it started showing up more in industry.
 
  • #14
... so I wouldn't be surprised if it started showing up more in industry.

Thats good to know.

Thanks
Matt
 
  • #15
No guarantees ;)
 

1. How can I determine which parts of my code are slowing down the overall execution time?

There are several ways to identify the bottlenecks in your MATLAB code. One option is to use the built-in profiler tool, which provides detailed information on the time and memory usage of each function in your code. Another approach is to use the tic and toc commands to measure the execution time of specific sections of your code.

2. Are there any built-in functions or tools in MATLAB that can help speed up my code?

Yes, there are several functions and tools in MATLAB that are designed for optimizing code performance. These include vectorization, parallel computing, and preallocation. Additionally, MATLAB has a function called "mlint" that can identify potential optimizations in your code.

3. Is it better to use built-in functions or write my own code for better performance?

In general, it is recommended to use built-in functions in MATLAB as they are optimized for performance and have been extensively tested. However, in some cases, writing your own code may be more efficient, especially if you have a specific algorithm or calculation that is not available in a built-in function.

4. Can using more memory help speed up my code?

In some cases, increasing the amount of memory available to MATLAB can improve code performance. This is particularly true for memory-intensive operations such as large matrix multiplications. However, in most cases, memory usage alone will not significantly speed up your code.

5. Are there any other tips or tricks for optimizing MATLAB code?

Yes, there are several other strategies you can use to improve the performance of your MATLAB code. These include using efficient data structures, reducing unnecessary computations, and avoiding excessive use of loops. It can also be helpful to consult with other MATLAB users or online resources for additional tips and techniques.

Similar threads

  • MATLAB, Maple, Mathematica, LaTeX
Replies
4
Views
1K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
4
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
5
Views
1K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
9
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
6
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
5
Views
7K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
8
Views
1K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
3
Views
2K
  • Introductory Physics Homework Help
Replies
27
Views
2K
  • Introductory Physics Homework Help
Replies
12
Views
1K
Back
Top