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

2 次查看(过去 30 天)
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 个评论
Steven Lord
Steven Lord 2021-10-5
Do you need it to be displayed that way or do you just need it to perform those computations?
If you had a Y array with a thousand elements, do you really want that large a function handle display?
Clara Vivian
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 个)

Voss
Voss 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
Clara Vivian 2021-10-5
编辑:Clara Vivian 2021-10-6
@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
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])

Steven Lord
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

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by