Trying to speed up some MATLAB code

Click For Summary

Discussion Overview

The discussion revolves around optimizing MATLAB code for calculating the forward kinematics of a robotic arm, specifically focusing on improving the efficiency of matrix multiplications involved in the computation. Participants explore various approaches, including vectorization, sparse matrices, and comparisons with C programming.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Experimental/applied

Main Points Raised

  • One participant describes their MATLAB implementation for forward kinematics using a loop for matrix multiplication and expresses a desire to eliminate the loop for efficiency.
  • Another participant mentions the Numerical Recipes website as a resource but notes potential issues with the routines provided.
  • A participant suggests writing a C version of the code for speed comparisons, indicating a belief that C will outperform MATLAB.
  • Results from a participant's tests show significant differences in execution time for matrix multiplications, with C being much faster than both MATLAB and Octave.
  • Some participants share experiences of using MATLAB versus C, highlighting the trade-offs between ease of use and execution speed.
  • One participant raises a question about memory allocation in MATLAB, suggesting that pre-allocating matrices could improve performance.
  • Another participant mentions considering Python as an alternative to MATLAB, noting its straightforward syntax but expressing concerns about its 3D plotting capabilities.
  • Discussions about Scilab reveal mixed experiences, with some participants finding it usable but acknowledging MATLAB's industry standard status.

Areas of Agreement / Disagreement

Participants express a range of opinions regarding the efficiency of different programming languages for matrix operations, with no consensus on the best approach for the original MATLAB problem. Some participants agree on the advantages of C for speed, while others discuss the merits of MATLAB and alternatives like Python and Scilab.

Contextual Notes

Participants mention various programming environments and libraries, indicating that performance may depend on specific implementations and configurations. There are references to the limitations of certain tools and the need for further exploration of alternatives.

Who May Find This Useful

This discussion may be useful for engineers and programmers interested in optimizing numerical computations, particularly those working with robotic systems or matrix operations in MATLAB and other programming languages.

sprince09
Messages
8
Reaction score
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
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
 
Yeah, I think I'm just going to write a 2nd copy of the code in C to do speed comparisons with. Thanks anyway
 
If you can, let us know how "quick" the C code is compared to MatLab.

Thanks
Matt
 
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.
 
WOW! Those times are very different.

Thanks for the information.

Matt
 
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.
 
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...
 
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 ;)
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 4 ·
Replies
4
Views
7K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 6 ·
Replies
6
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
Replies
5
Views
8K
  • · Replies 2 ·
Replies
2
Views
5K