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

1 view (last 30 days)
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 Comments
Steven Lord
Steven Lord on 5 Oct 2021
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 on 6 Oct 2021
actually I want to make a function that has the output of newton and lagrange interpolation polynomials with the degree of k. @Steven Lord

Sign in to comment.

Answers (3)

Voss
Voss on 5 Oct 2021
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 Comment
Clara Vivian
Clara Vivian on 5 Oct 2021
Edited: Clara Vivian on 6 Oct 2021
@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]

Sign in to comment.


Mathieu NOE
Mathieu NOE on 5 Oct 2021
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 on 6 Oct 2021
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

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!