# I want to make a function of x that uses loop for (x-x(i))

조회 수: 2(최근 30일)
Clara Vivian 2021년 10월 5일
답변: Steven Lord 2021년 10월 6일
For example, if i have an array x = [1 2 4]
I want to get the output, which is a function that looks something like this,
f =@(x) (x-1) + (x-1)*(x-2) + (x-1)*(x-2)*(x-4)
I am currently trying to get it through this code below, but I still haven't found the way to make the output like the above
%%
x = [1 3 5];
a = 2;
b = 3;
for i = 1:3
c = x(i);
fc = @(a,b,c) str2func(sprintf('@(x) %.3f.*x.^2 + %.3f + (x - %.3f)',a,b,c));
a = a + 1;
b = b + 1;
f = fc(a,b,c)
end
and also, what if for example i want to add another array, Y = [ 3 4 6]
and i want the output to look like this:
Y(1) * (x-1) + Y(2) * (x-1)*(x-3) + Y(3) * (x-1)*(x-3)*(x-5)
with the X = [1 3 5]
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Clara Vivian 2021년 10월 6일
actually I want to make a function that has the output of newton and lagrange interpolation polynomials with the degree of k. @Steven Lord

댓글을 달려면 로그인하십시오.

### 답변(3개)

Benjamin 2021년 10월 5일
Here's one way:
mono_x = arrayfun(@(x)sprintf('(x-%.3f)',x),x,'UniformOutput',false);
prod_x = arrayfun(@(i)sprintf('%s*',mono_x{1:i}),1:numel(x),'UniformOutput',false);
prod_x = cellfun(@(x)x(1:end-1),prod_x,'UniformOutput',false);
prod_x(end+1,:) = {'+'};
prod_x = strcat(prod_x{:});
prod_x(end) = [];
f = str2func(['@(x)' prod_x]);
##### 댓글 수: 1표시숨기기 없음
Clara Vivian 2021년 10월 5일
@Benjamin what if for example i want to add another array, Y = [ 3 4 6]
and i want the output to look like this:
Y(1) * (x-1) + Y(2) * (x-1)*(x-3) + Y(3) * (x-1)*(x-3)*(x-5)
with the X = [1 3 5]

댓글을 달려면 로그인하십시오.

Mathieu NOE 2021년 10월 5일
hello
my 2 cents suggestion :
%%
x = [1 3 5];
a = 2;
b = 3;
%%%% main loop
strc = [];
for i = 1:3
str = ['(x-' num2str(x(i)) ')'];
strc = [strc str '.*'];
end
strc2 = ['@(x) ' strc(1:end-2)];
fhandle = str2func(strc2)
%numerical application
fhandle(a)
fhandle(b)
fhandle([a b])
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

댓글을 달려면 로그인하십시오.

Steven Lord 2021년 10월 6일
If the display isn't important:
x = [1 2 4];
f1 = @(value) sum(cumprod(value-x))
f1 = function_handle with value:
@(value)sum(cumprod(value-x))
f2 =@(x) (x-1) + (x-1)*(x-2) + (x-1)*(x-2)*(x-4)
f2 = function_handle with value:
@(x)(x-1)+(x-1)*(x-2)+(x-1)*(x-2)*(x-4)
To spot check:
[f1(3); f2(3)]
ans = 2×1
2 2
[f1(pi); f2(pi)]
ans = 2×1
2.4878 2.4878

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

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

Start Hunting!

Translated by