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);
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

36.7% Correct | 63.3% Incorrect
Last solution submitted on Nov 29, 2016

Problem Comments

Solution Comments

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!

Join the 15-year community celebration.

Play games and win prizes!

Learn more