How to code this problem?

For example,
I got
A=[ 1 2 4 5 1 .......]
I want to calculate:
X1=(x-2)(x-4)(x-5)(x-1).....
X2=(x-1)(x-4)(x-5)(x-1)....
X3=(x-1)(x-2)(x-5)(x-1)....
And so on
So how can I code it on Matlab?
Thank you very much!

댓글 수: 2

James Tursa
James Tursa 2019년 5월 10일
What have you done so far? What specific problems are you having with your code? Are you after a symbolic result, or a numeric result for a specific value of x?
Hi, thank you for your answer
I've tried
syms x
X=[1 2 3]
n=size(X,2)
A=1
for i=2:n
A=A*(x-X(i))
end
And it gives me A=(x-2)(x-3)
So I'm finding a way to make the program also gives me B=(x-1)(x-3) and C=(x-1)(x-2) and generalize it so when I input any vector X with any n=size(X,2) it can give me the full answer.
Specifically, I'm doing Lagrange Interpolation
Thank you
(sorry for my English)

답변 (1개)

James Tursa
James Tursa 2019년 5월 10일

0 개 추천

E.g.,
syms x
A = [1 2 4 5];
n = numel(A);
P = prod(x-A);
X = cell(n,1);
for k=1:n
X{k} = P / (x-A(k));
end
This gives a cell array
>> X{1}
ans =
(x - 2)*(x - 4)*(x - 5)
>> X{2}
ans =
(x - 1)*(x - 4)*(x - 5)
>> X{3}
ans =
(x - 1)*(x - 2)*(x - 5)
>> X{4}
ans =
(x - 1)*(x - 2)*(x - 4)

댓글 수: 10

The program gives me:
X =
4×1 cell array
{1×1 sym }
{0×0 double}
{0×0 double}
{0×0 double}
How can I convert it?
Thank You :D
James Tursa
James Tursa 2019년 5월 10일
편집: James Tursa 2019년 5월 10일
What is the A variable you are using? What version of MATLAB are you using?
John Amitage
John Amitage 2019년 5월 10일
My Matlab version is R2018a
James Tursa
James Tursa 2019년 5월 10일
And A?
John Amitage
John Amitage 2019년 5월 10일
Oh I am sorry, may I ask you what is "A variable"?
James Tursa
James Tursa 2019년 5월 10일
Look at your original post, you have this variable
A=[ 1 2 4 5 1 .......]
I am asking you what "A" variable you are using with the code I have given you. The code works for me as I have demonstrated.
John Amitage
John Amitage 2019년 5월 10일
I copied your code but without the semicolon because the program display nothing if it's there
Screenshot (46).png
James Tursa
James Tursa 2019년 5월 10일
편집: James Tursa 2019년 5월 10일
So, what is the problem? It looks like the code works for you. What does this show after you run the code:
X{1}
X{2}
X{3}
X{4}
Aren't those the polynomials you want?
John Amitage
John Amitage 2019년 5월 10일
ahh I understand now, i'm so sorry for taking your time :D
Thank you and have a good day !
James Tursa
James Tursa 2019년 5월 10일
No problem! Note that it is easy to generalize this to an arbitrary sized "A" variable by using a cell array. It would be horrendous to try and implement this with named variables X1, X2, etc.

이 질문은 마감되었습니다.

제품

릴리스

R2018a

질문:

2019년 5월 10일

마감:

2021년 8월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by