Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate symbolic expression in MATLAB

Tags:

matlab

I am trying to evaluate a function which is an infinite cosine series at some input values.

EDIT: Posting an image to describe what the infinite series looks like enter image description here

I wrote the following code to describe it in MATLAB.

function func = cosfun_hat(a,i)
    syms m x;

    assume(m,'integer');
    assumeAlso(m > 0);

    sum(x) = sqrt(1-a^2)*symsum(sqrt(2)*a^m*cos(i*sym(pi)*x*2^m+1),m,0,Inf);
    func(x) = sum(x);
end

I want to evaluate the returned 'function' func to get numerical values for some input range say x_in = 0:0.001:1.

%Trying to evaluate func at x = 2
%In the command window I write
func = cosfun_hat(0.5,2);
func(2)

which returns the symbolic expression:

(2^(1/2)*3^(1/2)*sum((1/2)^m*(exp(- pi*exp(m*log(2))*4*i - i)/2 + exp(pi*exp(m*log(2))*4*i + i)/2), m == 0..Inf))/2

I tried using subs to evaluate the expression:

%In the command window
syms y;
w(y) = func(y);
y = 2;
subs(w);

But that returns the same symbolic expression. I am quite new to symbolic MATLAB.

Thanks!

EDIT Based on the comment by @NickyMattsson I tried

vpa(func(2)) 

which returns the numerical value of the expression. However, vpa(func(0.1)) returns a symbolic expression:

ans =

1.2247448713915890490986420373529*numeric::sum((1/2)^m*(exp(- (pi*exp(m*log(2))*i)/5 - i)/2 + exp((pi*exp(m*log(2))*i)/5 + i)/2), m == 0..Inf)

The same problem with using double(func(0.1)), double doesn't return anything and is stuck.

like image 404
Vizag Avatar asked Oct 17 '22 16:10

Vizag


1 Answers

Figured out a way to do it without using symbolic MATLAB.

function func = cosfun_hat(a,i,x)
    m = 0;
    sum = zeros(1,length(x));
    sum2 = Inf(1,length(x));
    while max(sum2-sum) > 1e-16
        disp(m);
        sum2 = sum;
        sum = sum + sqrt(1-a^2)*sqrt(2)*a^m*cos(i*pi*x*2^(m+1));
        m = m+1;

    end
    func = sum;
end

The sum converges inside 100 iterations.

Now if I do,

%In command window
x_in = -2:0.001:2;
f = cosfun_hat(0.6,2,x_in);
plot(x_in,f);

I get the plot:

enter image description here

Thanks everyone for your help!

like image 58
Vizag Avatar answered Oct 20 '22 23:10

Vizag