File Exchange

image thumbnail

Anti-diagonal matrix traversal

version 1.4.0.0 (1.43 KB) by Loïc
This function allows you to traverse a square matrix along the anti-diagonal.

2 Downloads

Updated 21 May 2010

View Version History

View License

This function takes as an input a square matrix and returns two outputs. The first is a vector containing the matrix values starting in the (1,1) entry and progressing along the anti-diagonal elements. A second output gives the sum of the elements along the anti-diagonals.
For example:
a = [1 2 3; 4 5 6; 7 8 9];
[b,c] = diagtrav(a);
b = [1 2 4 3 5 7 6 8 9];
c = [1 6 15 14 9];

Cite As

Loïc (2021). Anti-diagonal matrix traversal (https://www.mathworks.com/matlabcentral/fileexchange/27688-anti-diagonal-matrix-traversal), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (2)

Loïc

Thank you for your suggestion, this is my first submission. I have updated the file.

Matt Fig

As it is, you have some deficiencies. There is no H1 line. The help is non-standard in its location. There is no input checking: if the function is for square matrices then you should check to see if the input is square. Your algorithm works well, except you cripple the speed by not pre-allocating your return arrays before the loops. Look at the difference:

>> M = round(rand(400)*300);
>> tic,[P,Q]=diagtrav(M);toc % No pre-allocation
Elapsed time is 134.937511 seconds.
>> tic,[P,Q]=diagtrav(M);toc % With pre-allocation
Elapsed time is 0.014006 seconds.

You should pre-allocate the return arrays!

MATLAB Release Compatibility
Created with R2009b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!