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

Basics on Vectors
- 11 Problems
- 7937 Finishers
- Find the sum of all the numbers of the input vector
- Select every other element of a vector
- Arrange Vector in descending order
- Inner product of two vectors
- Get the length of a given vector
- Find max
- Whether the input is vector?
- Flip the vector from right to left
- Create a vector
- Doubling elements in a vector
- Vector creation
Problem Recent Solvers299
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!