Problem 61149. Convert a diagonal representation of a matrix element to linear index or subscripts

Elements in matrices in MATLAB can be retrieved by linear index or subscripts. For example, the 1 in the matrix below has a linear index of 18 and subscripts of [3, 4], and the 2 has a linear index of 10 and subscripts of [5, 2].
0 0 0 0 0
0 0 0 0 0
0 0 0 1 0
0 0 0 0 0
0 2 0 0 0
Let’s add another way to refer to elements in a matrix by specifying the diagonal d and position k along the diagonal. As in the DIAG command, d = 0 is the main diagonal, d > 0 is above the main diagonal, and d < 0 is below the main diagonal. For the matrix above, the 1 would have [d, k] = [1, 3], and the 2 would have [d, k] = [-3, 2].
Write a function to convert the diagonal representation of an element to either a linear index or subscripts. The function will take three arguments: sz, the size of the two-dimensional matrix; diagvec, the diagonal representation [d, k]; and indx, a logical variable indicating linear index (true) or subscripts (false). If the diagonal representation puts the element out of the bounds of the matrix, set the linear index to NaN and subscripts to [NaN, NaN].

Solution Stats

41.67% Correct | 58.33% Incorrect
Last Solution submitted on Jan 06, 2026

Solution Comments

Show comments

Problem Recent Solvers5

Suggested Problems

More from this Author319

Community Treasure Hunt

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

Start Hunting!