Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Trying to speed up some MATLAB code

  1. Dec 29, 2009 #1
    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 (Text):

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

    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: Dec 29, 2009
  2. jcsd
  3. Jan 11, 2010 #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.


  4. Jan 11, 2010 #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
  5. Jan 11, 2010 #4
    If you can, let us know how "quick" the C code is compared to MatLab.

  6. Jan 11, 2010 #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 (Text):

    % MATLAB test code

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

    for i = 1:30
        for j = 1:1000000
            C = A * B;


    C Code:

    Code (Text):

    // 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
        return 0;



    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


    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.
  7. Jan 14, 2010 #6
    WOW! Those times are very different.

    Thanks for the information.

  8. Jan 14, 2010 #7


    User Avatar
    Science Advisor

    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.
  9. Jan 14, 2010 #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...
  10. Jan 15, 2010 #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.
  11. Jan 15, 2010 #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.
  12. Jan 15, 2010 #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: Jan 15, 2010
  13. Jan 15, 2010 #12
    What did you think of Scilab? I just started using it for simple calculations.

  14. Jan 15, 2010 #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.
  15. Jan 15, 2010 #14
    Thats good to know.

  16. Jan 15, 2010 #15
    No guarantees ;)
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Similar Discussions: Trying to speed up some MATLAB code