How do I declare a symbolic matrix in Octave?

TwentyMiles picture TwentyMiles · Mar 18, 2010 · Viewed 36.2k times · Source

In MatLab, you can declare symbols pretty easily:

syms a,b
mat = [a,b]

I'm getting an error, however, when I try to replicate this in Octave. This is the code I'm using:

> symbols
> a = sym("a")
a =

a
> b = sym("b")
b =

b
> mat = [a,b]
error: octave_base_value::resize (): wrong type argument `ex'
error: octave_base_value::resize (): wrong type argument `<unknown type>'
octave-3.2.3.exe:4:C:\Octave\3.2.3_gcc-4.4.0\bin

How do you declare a symbolic matrix in octave?

Answer

Dave Sims picture Dave Sims · Mar 9, 2016

If you don't already have the symbolic package, download it. From Octave command line, or gui command line. e.g.

octave> pkg install -forge symbolic

If you have python and sympy installed, that will install the package for you from octave forge. I used google to figure out how to get sympy installed, hit me up if you need help.

With symbolic package installed, use "pkg load" to import the package functions, and then use syms function to declare symbols.

octave> pkg load symbolic

octave> syms a b

This defined symbols a and b.

octave> syms
Symbolic variables in current scope:
  a
  b

"syms" by itself will print all the symbols you have defined.

octave> mat = [a,b]
mat = (sym) [a  b]  (1×2 matrix)

octave:34> mat * 2
ans = (sym) [2⋅a  2⋅b]  (1×2 matrix)

I found this package very helpful in computing Rotation matrices for my Robotic Manipulators class. Hope this helps.

Here's part of my script for more examples:

pkg load symbolic
syms psi phi theta psidot phidot thetadot

RzPsi = [[cos(psi), -sin(psi), 0]; [sin(psi), cos(psi), 0]; [0,0,1]]
RyTheta = [[cos(theta), 0, sin(theta)];[0,1,0];[-sin(theta), 0, cos(theta)]]
RzPhi = [[cos(phi), -sin(phi), 0]; [sin(phi), cos(phi), 0]; [0,0,1]]

RzPsi = (sym 3×3 matrix)

  ⎡cos(ψ)  -sin(ψ)  0⎤
  ⎢                  ⎥
  ⎢sin(ψ)  cos(ψ)   0⎥
  ⎢                  ⎥
  ⎣  0        0     1⎦

RyTheta = (sym 3×3 matrix)

  ⎡cos(θ)   0  sin(θ)⎤
  ⎢                  ⎥
  ⎢   0     1    0   ⎥
  ⎢                  ⎥
  ⎣-sin(θ)  0  cos(θ)⎦

RzPhi = (sym 3×3 matrix)

  ⎡cos(φ)  -sin(φ)  0⎤
  ⎢                  ⎥
  ⎢sin(φ)  cos(φ)   0⎥
  ⎢                  ⎥
  ⎣  0        0     1⎦

octave> RzPhi * RyTheta
ans = (sym 3×3 matrix)

  ⎡cos(φ)⋅cos(θ)   -sin(φ)  sin(θ)⋅cos(φ)⎤
  ⎢                                     ⎥
  ⎢sin(φ)⋅cos(θ)   cos(φ)   sin(φ)⋅sin(θ)⎥
  ⎢                                     ⎥
  ⎣   -sin(θ)        0        cos(θ)    ⎦