piecewise symbolic function within a symbolic matrix

Hallo, I would like to construct a matrix P whose elements depend on x (a vector that varies with time). Some elements of P are piecewise functions of x. The code is just to test whether P can be updated. Any help will be much appreciated.
sym x
P = sym(zeros(3,3)) %create empty symbolic matrix
P(1,1) = sym('1/(1+exp(-4.3*x(1)))')
P(2,1) = sym('0.2*x(2)')
P(3,1) = sym('0.4*sin(0.0192+x(3))')
P(1,2) = sym('1/(1+exp(11.8*x(2)))')
P(2,2) = .3435
P(3,2) = sym('.02 + (x(3)>=.04)*(.66*x(3))') %piecewise
x = [.5, .5, .1]
eval(P)
But I get an error due to the piecewise function (without it, P easily updates):
Error using sym/eval (line 11)
Error: Unbalanced or unexpected parenthesis or bracket.
Outside of the sym function, .02 + (x(3)>=.04)*(.66*x(3)) works all right.
I have also tried:
sym('piecewise([x(3)<.04,.02],[x(3)>=.04,0.02+0.66*x(3)])')
but still no go...I wonder what I am doing wrong? Thanks for your time

 Réponse acceptée

You may not be doing anything actually ‘wrong’, but eval may not be your best choice.
Replace it with:
vpa(P)
to get it to work without errors.

5 commentaires

Andy
Andy le 8 Juil 2014
Modifié(e) : Andy le 8 Juil 2014
I tried your suggestion:
...
x = [.5, .5, .1]
P1 = vpa(P)
But P1 is still a symbolic matrix (i.e. not a matrix of actual function values)
The Symbolic Math Toolbox may not be the best way to do it if you simply want a numeric answer. I copy-pasted the elements of your matrix to a numeric matrix and made an anonymous function out of it:
x = [.5, .5, .1]
P = @(x) [(1/(1+exp(-4.3*x(1)))) (1/(1+exp(11.8*x(2)))); (0.2*x(2)) .3435; (0.4*sin(0.0192+x(3))) (.02 + (x(3)>=.04)*(.66*x(3)))]
Px = P(x)
produces:
Px =
895.6688e-003 2.7320e-003
100.0000e-003 343.5000e-003
47.5672e-003 86.0000e-003
Does that do what you want?
Andy
Andy le 13 Nov 2014
Thanks for this.
My pleasure!
The sincerest expression of appreciation here on MATLAB answers is to Accept the answer that most closely solves your problem.
Inside the Symbolic Toolbox, the result of comparisons is true (a logical value) or false (a logical value) or FAIL (which is its own object type) . The results are not numeric 0 or numeric 1, so
sym('.02 + (x(3)>=.04)*(.66*x(3))')
will not do what is desired.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by