MATLAB Answers

Plotting several values returned by a function.

4 views (last 30 days)
Yuval
Yuval on 25 Oct 2013
Commented: Yuval on 26 Oct 2013
Hi, I wrote the following function for the interpolation polynomial of log(x):
function pol = Lagrange1(x)
dim1 = [1, 2, 4];
dim2 = [0, 0.693, 1.386];
pol1 = dim2(1)*(x-dim1(1))*(x-dim1(3))/[(dim1(1)-dim1(2))*(dim1(1)-dim1(3))];
pol2 = dim2(2)*(x-dim1(1))*(x-dim1(3))/[(dim1(2)-dim1(1))*(dim1(2)-dim1(3))];
pol3 = dim2(3)*(x-dim1(1))*(x-dim1(2))/[(dim1(3)-dim1(1))*(dim1(3)-dim1(2))];
pol = pol1 + pol2 + pol3;
I'd like to plot the value it returns for x = 0.01:0.01:12. How may I go about it, please? I have tried using ordinary plot(), in a loop even, to no avail.

Answers (1)

Jie
Jie on 26 Oct 2013
You could have plotted the result in a loop (if you have used the function file correctly). But I suggest u not do this.
In order to make this right and simple, change your function file into the following:
function pol = Lagrange1(x)
dim1 = [1, 2, 4];
dim2 = [0, 0.693, 1.386];
pol1 = dim2(1)*(x-dim1(1)).*(x-dim1(3))/[(dim1(1)-dim1(2))*(dim1(1)-dim1(3))];
pol2 = dim2(2)*(x-dim1(1)).*(x-dim1(3))/[(dim1(2)-dim1(1))*(dim1(2)-dim1(3))];
pol3 = dim2(3)*(x-dim1(1)).*(x-dim1(2))/[(dim1(3)-dim1(1))*(dim1(3)-dim1(2))];
pol = pol1 + pol2 + pol3;
only three dots were added. But now your function file is vector/matrix supported.( Your previous file is only scalar supported ) And then use this following code:
x = 0.01:0.01:12;
y=Lagrange1(x);
figure,plot(x,y)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by