1
votes

How can I use variables inside a symbolic variable in Matlab?

For example, I have the following code:

function f = constr_fourier(vec);
dim=prod(size(vec));
n=(dim-1)/2;
a=@(k) vec(k+1);
b=@(k) vec(n+k-1);

f = @(x) subs(a,{k,0})/2 + symsum(subs(a,{k,i})*cos(i*x) + ...
subs(b,{k,i})*sin(i*x),i,1,n);

In which I want to recover the Fourier series given a vector of coefficients vec. I want to replace the actual values from vec into the symbolic expression of the function. I tried that with subs but it doesn't work, or I didn't use it right.

What is the right way to do this?

[edit] I have tried

f = @(x) subs(a,k,0)/2 + symsum(subs(a,k,i)*cos(i*x) + ...
subs(b,{k,i})*sin(i*x),i,1,n);

but the result is with subs(...) and not with the numerical value of a(k).

I have tried also a different variant, which gives the a result but in a wrong way...

function f = constr_fourier(w);
syms x k n u c t vector;

evalin(symengine,'assume(k,Type::Integer)');

dim=prod(size(w));
m=(dim-1)/2;

a0=w(1);
a= w(2:m+1);
b= w(m+2:2*m+1);

u=@(k,vector) vector(k);

fs = @(x,n,c) c/2 + symsum(subs(u,{k,vector},{t,a})*cos(t*x) + subs(u,{k,vector},          {t,b})*sin(t*x),t,1,n);

f= fs(x,m,a0);

I tried to use the function u=@(k,vec) vec(k) instead of the initial one. When I use subs(u,{k,vector},{t,a}) separately in the terminal, it works ok, but here it doesn't...

I get the result as a vector of two function instead of a function.

2

2 Answers

4
votes

subs is indeed the right way, you're just using it wrong.

There are three input arguments for subs: the symbolic expression, the parameters to substitute and their new value. There is one exception though: if there are two input arguments, subs replaces the default symbolic parameter in the expression with the second argument.

Anyway, it seems that you're missing the new values in subs, so it doesn't behave like you meant it to. I think that it is supposed to look like this:

subs(a, k, 0)

etc...

As a side note, it is sufficient (and more elegant) to use subs only once. Compute your entire symbolic expression and then use subs once. So instead of:

subs(a, ...) + subs(b, ...)

I recommended you to do this instead:

subs(a + b, ...)
0
votes

If you define

a=@(k) vec(k+1);

then a is not a symbolic expression, but a function, and to get a specific value for k into that, you cannot use subs. Instead, you have to call the function a:

a(1)

f = @(x) a(0)/2 + sum(@(i) a(i)*cos(i*x) + b(i)*sin(i*x),1,n)