Asked by Tejas Adsul
on 16 May 2018

I can use

x = sym('x',[n,1]);

y = sym('y',[n,1]);

to create symbolic variables of length 'n'.

I would like to create symbolic functions x(t) and y(t) of the same length. But the above syntax doesn't accept an argument.

x = sym('x(t)',[n,1]);

y = sym('y(t)',[n,1]);

gives an error 'If the second argument specifies the dimensions of the generated symbolic vector or matrix, then the first argument must be a character vector specifying the base name for vector or matrix elements. It must be a valid variable name.'

The only way to create them seems to be

syms x(t) y(t)

But I need them to be of length 'n'. The rest of my code depends on the value of 'n'. It contains odes which consist of diff(x(i),t) and diff(y(i),t), where 'i' would vary from 1 to 'n'. How can I define x(t) and y(t) of length 'n'?

What I desire in the end is this:

Suppose n=3. If I knew this, then I would do

syms x1(t) x2(t) x3(t) y1(t) y2(t) y3(t)

Here, I have created a total of 6 functions. Then, if I have some polynomial

p = x1^3 + 5y2 + 4x2^4 + y3^2

I would be able to write an ode of the form

ode1 = diff(x1,t) == p

ode2 = diff(x2,t) == p

But I don't know 'n'. I would like to create a code which creates the corresponding functions in a loop, once I know 'n'. So, if I put n=4, I should immediately get 8 functions: x1,x2,x3,x4,y1,y2,y3,y4, all functions of 't'. How do I do this?

Answer by Walter Roberson
on 16 May 2018

Edited by Walter Roberson
on 16 May 2018

Accepted Answer

You will need to loop or equivalent creating the symbolic functions. There is no MATLAB syntax for what you want.

T = sprintfc('y%d(t)', 1:n);

syms(T{:})

Tejas Adsul
on 16 May 2018

Okay, this works. But can't I put these symbolic functions in a vector or an array?

Tejas Adsul
on 16 May 2018

Walter Roberson
on 16 May 2018

n = 5;

T = sprintfc('y%d(t)', 1:n);

syms(T{:})

V = [y1 y2 y3];

V(3)

ans =

[ y1(3), y2(3), y3(3)]

Any time you have a vector of functions, there is ambiguity about whether using () means indexing or means calling with a parameter. In old versions of MATLAB, a vector of function handles treated () as indexing, which did not permit calling the functions without assigning to a variable. Eventually, MATLAB simply banned making a vector of function handles, requiring that they be put into cell arrays rather than plain vectors.

The Symbolic Toolbox took the opposite choice, that () is treated as calling, which does not permit indexing except by using children() to break them out into individual cell array entries. You should probably just make them individual cell array entries -- or leave them as expressions instead of as functions.

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.