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

1 Ansicht (letzte 30 Tage)
Clara Vivian
Clara Vivian am 5 Okt. 2021
Beantwortet: Steven Lord am 6 Okt. 2021
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 Kommentare
Steven Lord
Steven Lord am 5 Okt. 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 am 6 Okt. 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

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Voss
Voss am 5 Okt. 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 Kommentar
Clara Vivian
Clara Vivian am 5 Okt. 2021
Bearbeitet: Clara Vivian am 6 Okt. 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]

Melden Sie sich an, um zu kommentieren.


Mathieu NOE
Mathieu NOE am 5 Okt. 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 am 6 Okt. 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

Kategorien

Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by