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 commentsProblem Recent Solvers299
Suggested Problems
-
Find all elements less than 0 or greater than 10 and replace them with NaN
15609 Solvers
-
Back to basics 12 - Input Arguments
605 Solvers
-
465 Solvers
-
574 Solvers
-
2385 Solvers
More from this Author11
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!