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

Learn moreOpportunities for recent engineering grads.

Apply TodayGiven 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

28 correct solutions
43 incorrect solutions

Last solution submitted on Dec 22, 2014

1 player likes this problem

1 player likes this solution

2 Comments

Jean-Marie SAINTHILLIER
on 11 Oct 2012

I like the try/catch with ans

Khaled Hamed
on 12 Oct 2012

It seems Matlab allows for many useful tricks. I was surprised at the behavior of 'diag' in the leading solution.

5 Comments