help needed in creating a better "diag" function

edited December 2009 in Science & Tech
Hi,
I need to extract the main diagonal of a matrix without using the function "diag". This is not a homework exercise for studying loops in MATLAB or something like that, the point is to create a function with lower complexity than "diag" has. I need to run a pretty heavy code with large loops so every micro-second matters. I've already checked the natural way to do this using this loop:
for i=1:length(a)
my_diag(i)=a(length(a)*(i-1)+i)
end

Unsurprisingly the diag function is more effiecient by far.
Any ideas? I can't think of a way to avoid using a loop here...

Thanks!

Comments

  • drasnordrasnor Starship Operator Hawthorne, CA Icrontian
    edited December 2009
    Doesn't diag() build a diagonal matrix from a vector? Your code doesn't appear to do that. At any rate, you can start by preallocating my_diag to the same size as a. If you don't preallocate then MATLAB runs a memory allocation routine on each loop iteration which will hose your loop efficiency.

    Since this is not an iterative process (i.e. my_diag(i) does not depend on my_diag(i-1)) you can unroll the loop and execute multi-core using multicore. However, multicore has latencies as well and may not be suitable for your application.

    Honestly though, if you really need speed though you shouldn't be using MATLAB. MATLAB is an interpreter written in Java running on a Java VM for two stages of high-level interpretation. It may be worth your while to implement your problem in a compiled language or portions of the problem as MEX extensions.

    -drasnor :fold:
  • shwaipshwaip bluffin' with my muffin Icrontian
    edited December 2009
    my_diag = A(1:size(A,1)+1:numel(A)); should be faster than the other code you have.

    But I'd guess that's what the matlab function is doing.
  • TheBaronTheBaron Austin, TX
    edited December 2009
    Never ever ever ever ever ever ever ever ever use for loops in Matlab. Everything you want to do can be done with clever matrix or vector implementation.

    With that said, Swwaip is right (as far as my 99% drunk mind can tell). My feeling is that is that most likely diag is not your problem. More often there is a convoluted while loop or something similar which is the bulk of your program and, in fact, sucks.
  • drasnordrasnor Starship Operator Hawthorne, CA Icrontian
    edited December 2009
    Here's an easy way to tell if you don't need to use looping: if a result from a later calculation in the loop doesn't depend on a calculation made earlier in the loop then you don't need to loop.

    -drasnor :fold:
Sign In or Register to comment.