0
$\begingroup$

I am new to octave and still learning what I can and cannot do with it. I am asked to write a following function ('trigmin'):

[a, b, c, info]=tigmin(x,y)

Where x, y are vectors of the same length (let's say n) and the function output is the triple [a, b, c] where the triple minimizes the following expression $$\sum_{i=1}^n|a+b \cos(x_i)+c\sin(x_i)-y_i|^2$$

info = reports if the problem has non-unique solutions or if the vector sizes don't match.

The soln part is the one I am concerned with. Using symbols I would say a,b,c are symbols then build A matrix [ones(n),\cos{x},\sin{x},y] and multiply [a;b;c;-1][ones(n),\cos(x),\sin(x),y] to get a vector norm which I am trying to minmize. However in the class we haven't used symbolic package so I assume it is doable without using symbols.

Am I doing it right using symbols?

Is it possible not to use symbols? If so, then how?

The problem is simple and no loops are required

Any hints would be much appreciated.

$\endgroup$

1 Answer 1

2
$\begingroup$

You shouldn't be using symbolic package for this task. Also your usage of ones is going to produce n-by-n matrix of ones - which is not what you intended. Given the same problem, I wouldn't write a new function. I believe fminunc will be more than enough, but of course if this is an assignment you should follow the guidelines given in the assignment. Below is what I would do

x = rand(100,1); y = rand(100,1);
f = @(params) sum(abs(params(1)+params(2)*cos(x)+params(3)*sin(x)-y).^2);
initial_guess = [0,0,0];
[x,fval,exitflag,output] = fminunc(f, initial_guess);

x here contains the solution [a,b,c], fval is the function value at [a,b,c] i.e. f(x), exitflag and output are diagnostic information which may be of interest.

$\endgroup$
3
  • 4
    $\begingroup$ This is a linear least-squares problem; the backslash operator A \ b will solve it directly without need for fminunc. $\endgroup$ Commented Mar 10, 2020 at 13:32
  • $\begingroup$ That is true. I don't know the sizes of the vectors, so I preferred the err on the side of caution. If the vectors are large A\b may not be feasible. $\endgroup$ Commented Mar 10, 2020 at 14:43
  • $\begingroup$ I'd be willing to bet that the octave command will be faster than anything you can come up with though. $\endgroup$
    – EMP
    Commented Apr 30, 2020 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.