Problem 972. Set a diagonal
Given a matrix M, row vector v of appropriate length, and diagonal index d (where 0 indicates the main diagonal and off-diagonals are identified by positive and negative integers), return a new matrix where the specified diagonal of M is replaced by v. You may assume that v is the correct length for the specified diagonal. If d is not provided, assume it is zero.
For example,
M = magic(5);
setDiagonal(M,1:4,-1)
ans =
17 24 1 8 15
1 5 7 14 16
4 2 13 20 22
10 12 3 21 3
11 18 25 4 9
Solution Stats
Problem Comments
-
10 Comments
Show
7 older comments
Riccardo Dessì
on 25 Jun 2018
please, when you make use of test cases with floating point numbers specify a common precision, otherwise is impossible to pass the suite and people need to be noob! thx in advanced
Akrem Hadji
on 17 Oct 2020
Please add a precision threshold for floating numbers. Sometimes I get results with an error ~ e-17 close, but still not accepted.
Anton Casas
on 2 Nov 2020
Test cases with 2 input arguments can be very tricky for people without knowledge of nargin, and that is off-topic here. I think a hint should be added on the problem description.
Solution Comments
Show commentsGroup

Matrix Manipulation I
- 16 Problems
- 98 Finishers
- Remove the air bubbles
- Remove NaN ?
- N-Dimensional Array Slice
- Back to basics 21 - Matrix replicating
- Back to basics 23 - Triangular matrix
- Make an awesome ramp for a tiny motorcycle stuntman
- Flip the main diagonal of a matrix
- surrounded matrix
- Some Assembly Required
- Set some matrix elements to zero
- Matrix with different incremental runs
- Removing rows from a matrix is easy - but what about inserting rows?
- Rotate input square matrix 90 degrees CCW without rot90
- Permute diagonal and antidiagonal
- Operate on matrices of unequal, yet similar, size
- Reverse the elements of an array
Problem Recent Solvers299
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!