# Diagonal Matrix of a Piecewise Function

I have a piecewise function now I want to do a Matrix operation on it. How can I do that? For example, the Function is like below:

F[s_] := Piecewise[{{s^3, s <= 5}, {s^2, s > 5}}];
ds =   0.04 ;
n =  5 ;
s = Table[-2 + ds i, {i, 5} ];
DiagonalMatrix[F[s]]

Do I need to define the function in a different way?

• use DiagonalMatrix[F /@ s]
– kglr
Commented Jul 24, 2018 at 12:41
• @kglr Thank you very much! Commented Jul 24, 2018 at 12:42
• Or add Attributes[F] = Listable. Commented Jul 24, 2018 at 12:43
• @corey979...Thank you very much! Commented Jul 24, 2018 at 14:13

You can Map F on s:

DiagonalMatrix[F /@ s] // MatrixForm // TeXForm

$\left( \begin{array}{ccccc} -7.52954 & 0. & 0. & 0. & 0. \\ 0. & -7.07789 & 0. & 0. & 0. \\ 0. & 0. & -6.64467 & 0. & 0. \\ 0. & 0. & 0. & -6.2295 & 0. \\ 0. & 0. & 0. & 0. & -5.832 \\ \end{array} \right)$

Or give the function F the Attribute Listable and use F@s:

ClearAll[F]
F[s_] := Piecewise[{{s^3, s <= 5}, {s^2, s > 5}}];
SetAttributes[F, Listable]
DiagonalMatrix[F @ s] // MatrixForm // TeXForm

$\left( \begin{array}{ccccc} -7.52954 & 0. & 0. & 0. & 0. \\ 0. & -7.07789 & 0. & 0. & 0. \\ 0. & 0. & -6.64467 & 0. & 0. \\ 0. & 0. & 0. & -6.2295 & 0. \\ 0. & 0. & 0. & 0. & -5.832 \\ \end{array} \right)$