1
$\begingroup$

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?

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

1 Answer 1

2
$\begingroup$

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.