How can I solve optimization polynomial problem?

I am writing a program that can illustrate the adaption of a 4th-degree polynomial at 5 sampling points in an interval [0,a]. The function should be p = x(1) + x(2)*x + x(3)*x.^2 + x(4)*x.^3 + x(5)*x.^4. My problem is I cannot display the graph for every iteration until it meets the points. How can I do that?
Thanks in advance

2 Comments

Best to just show your code. Otherwise, we cannot know what you did wrong. That would force us to write complete code to do what you want to do.
If you force us to guess, then my current best guess is "You have a bug/mistake in your code."
So attach the code you have written to a comment, or to your original question by editing the question.
xdata = (0:1/4:1);
ydata = (1)*rand(5,1);
fun = @(x,xdata)x(1) + x(2)*xdata + x(3)*xdata.^2 + x(4)*xdata.^3 + x(5)*xdata.^4;
x0 = [ 0 0 0 0 0 ];
x = lsqcurvefit(fun,x0,xdata,ydata);
plot(xdata,ydata,'ko',xdata,fun(x,xdata),'b-')
coeff = [x(1) x(2) x(3) x(4) x(5)]
This is my code so far. Could you please correct it? Thanks!

Sign in to comment.

Answers (2)

It looks like it should work just fine. Why do you think it needs correction? lol.
Note that in real life, you would NEVER want to use lsqcurvefit for this! Just use polyfit. But this is homework. Ya gotta do what they tell you to do.
Your problem is that you have supplied a function handle that just computes fun. Yes, it does that well. But you were asked to do something extra at each iteration. The easiest way to do that is to use an m-file for your function. I know, its a pain in the neck. But you are doing all this because they make you do it. Again, you would not do this if you were just fitting a polynomial on a real problem.
So write an m-file function, one that takes the same inputs, does the same computation, returns the same results. BUT! Before it returns, have your function do as you were told. It looks like you want to do a plot of the function for the current set of values.
At the very end, you want it to do a pause. That will cause MATLAB to pause execution, waiting for you to hit the space bar before it will continue.

1 Comment

How can I change the coefficients everytime I press the keyboard input key? Do I need to stop every iteration to update the coefficients?

Sign in to comment.

This is a linear problem in x. The solution is readily given by
xdata = [0;0.25;0.5;0.75;1];
ydata = rand(5,1);
A = [ones(5,1), xdata, xdata.^2, xdata.^3, xdata.^4]
b = ydata;
x = A\b
No iteration needed.

Categories

Asked:

on 28 Oct 2018

Answered:

on 5 Nov 2018

Community Treasure Hunt

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

Start Hunting!