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
Added new test case 9 Oct. 2012
Are you missing some text from your example?
Test suggestion: Stick a zero in one of your v vectors and you'll eliminate some of the shorter answers.
Yes. All solutions with find don't work with 0 in v.
Thanks for the suggestions -- I updated the text, added a new test case and rescored.
@Nicholas Howe: The test suggestion meant: stick a 0 in v, and this 0 is meant to replace an entry of M that was unequal to 0. In other words: the new test-case doesn't make a difference (and hence is useless) if M is a null-matrix.
The cases with d=0 are working for me but your test cases are giving error..... What's this?
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
Please add a precision threshold for floating numbers. Sometimes I get results with an error ~ e-17 close, but still not accepted.
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 Solvers276
Suggested Problems
-
3823 Solvers
-
4515 Solvers
-
Create a square matrix of multiples
471 Solvers
-
Put two time series onto the same time basis
322 Solvers
-
5047 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!