# Using symbolic math to retain accuracy. Arrays

1 view (last 30 days)

Show older comments

Hi folks. I am trying to avoid numerical underflow using symbolic math.

Basically at some point in my algorithm I have a matrix Which I call C. The values of C are very lagre. Now I would like to perform some operations on C by using some inbuilt matlab functions, but without loosing numerical accuracy.

The operations in words, and then in code are as follows : 1. Take the exponential of each element of ( pointwise )

a=exp(-C)

2. Sum the rows of C, so we are left with a array of the sum of each row of

b=sum(a,2)

3. Take the pointwise logarithm of each element in the array .

ans=log(b)

Of course if the elements of C are too large then matlab reads the elements of as 0. I think there may be a way around this ( since in the end we take logarithms ) by using symbolic math, but I dont know how (im very new to matlab). Anyone have any ideas?

I would like to mention that in practice my matrix C is of dimension , and these operations are performed at every iteration of a for loop, hence Im worried that using symbolic math will increases the run time of my code too much.

##### 3 Comments

Bjorn Gustavsson
on 1 Dec 2021

### Answers (1)

Bjorn Gustavsson
on 1 Dec 2021

Factor out the average of each row of C. That should give you one term of the row-averages of C and then the sum of the logs of the exponential of the deviations relative to the average - these are hopefully small enough that your worries about nummerical accuracy are quenched...

HTH

##### 3 Comments

Bjorn Gustavsson
on 2 Dec 2021

TRY!

exp([1 2 3]) = exp(3).*exp([-2 -1 0]);

Sum and take the log of both expressions and compare the results:

S1 = log(sum(exp([1 2 3])));

S2 = log(exp(3)) + log(sum(exp([-2 -1 0])));

isequal(S1,S2) % Yeah this is a numerically dodgy comparison

TRY, if you "think", dont, check and work things out instead.

If this is not the expression you want your problem description is either too vague or inaccurate.

HTH

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!