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

CUP Challenge
- 11 Problems
- 4037 Finishers
- Length of a short side
- Triangle sequence
- Find a Pythagorean triple
- Is this triangle right-angled?
- Is this triangle right-angled?
- Area of an Isoceles Triangle
- Side of a rhombus
- Side of an equilateral triangle
- Area of an equilateral triangle
- Length of the hypotenuse
- Triangle sequence
- Is this triangle right-angled?
- Find a Pythagorean triple
- Is this triangle right-angled?
- Dimensions of a rectangle
Problem Recent Solvers299
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!