Working with vectors in matlab to form matrices

38 Views Asked by At

The problem is this. I'm taking Intro to Computational Math. It's been interesting, but I'm struggling to understand the matlab language. I've been a programmer for nearly 20 years, and this is the first time with a language that allows for working with arrays in this way.

As an introduction to the error function (named erf in MATLAB), we've fit a curve to the following polynomial

$$ p_4(t) = c_0 + c_1t + c_2t^2 + c_3t^3 + c_4t^4,t = \frac{k - 1}{10},k = 1,..,11 $$

Then, using that solve the linear system $\boldsymbol{A^TAc} = \boldsymbol{A^Ty}$. Solving, then, for the coefficients is quite simple. However, the homework isn't finished. I was taught that polynomials, like this, aren't particularly well-suited for the error function. So, the lesson asks further that we use the same data (i.e. $k=1,..,11$ and $t$) and fit to the curve:

$$ f(t) = c_0 + e^{t^2}(c_1 + c_2z + c_3z^2 + c_4z^3), z=\frac{1}{1+t} $$

This is where I'm struggling. My past programming experience isn't helping to solve this one well. I have this current statement for MATLAB which doesn't produce errors, but it also produces 11x35 matrix which is far too large.

k = 1:11;
t = (k - 1)/10;
B = [ones(length(t), 1), exp(t'.^2), exp(t'.^2)*(1/(1 + t')), exp(t'.^2)*(1/(1 + t')).^2, exp(t'.^2)*(1/(1 + t')).^3]

I based my statement from the one I used to define the original polynomial:

A = [ones(length(t),1), t', t'.^2, t'.^3, t'.^4];

How should I define this matrix, $\boldsymbol{B}$ (an 11x5), for use in the linear system?

1

There are 1 best solutions below

1
On BEST ANSWER

The problem is in the term 1/(1 + t'). Your t' is a vector, thus when you compute 1/(1 + t'), you have an 'inverse' of this vector, that is a row. What you need is the element-wise inverse given by 1./(1 + t').

The code

k = 1:11;
t = (k - 1)/10;
B = [ones(length(t), 1),...
    exp(t'.^2),...
    exp(t'.^2).*(1./(1 + t')),...
    exp(t'.^2).*(1./(1 + t')).^2,...
    exp(t'.^2).*(1./(1 + t')).^3];

yields $B$ beeing $11 \times 5$.

PS: By the way, I hope you do c=A\y and not c=inv(A'*A)*A'*y.