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 - Binary Logic
- 10 Problems
- 958 Finishers
- Find the longest sequence of 1's in a binary sequence.
- Convert given decimal number to binary number.
- Find out sum and carry of Binary adder
- Binary numbers
- Given an unsigned integer x, find the largest y by rearranging the bits in x
- Bit Reversal
- Relative ratio of "1" in binary number
- Binary code (array)
- Converting binary to decimals
- There are 10 types of people in the world
Problem Recent Solvers299
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!