Set a diagonal - MATLAB Cody - MATLAB Central

Problem 972. Set a diagonal

Difficulty:Rate
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

24.69% Correct | 75.31% Incorrect
Last Solution submitted on Mar 11, 2025

Problem Comments

Solution Comments

Show comments

Group

CUP Challenge Image
CUP Challenge
  • 11 Problems
  • 4037 Finishers

Problem Recent Solvers299

Problem Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
Go to top of page