help needed in creating a better "diag" function
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!
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!
0
Comments
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
But I'd guess that's what the matlab function is doing.
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.
-drasnor