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

4 ビュー (過去 30 日間)
Clara Vivian
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 件のコメント
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by