How do I create a loop to increment the number of terms of a function?

2 Ansichten (letzte 30 Tage)
There is this function m(x) that changes its size according to the number of elements in two vectors.
For instance, there are two vectors, a and b, which sizes and values are to be determined by the user. Let's say the user made each vector with 5 elements:
a = [1 2 3 4 5]
b = [6 7 8 9 10]
I want m(x) to be an inline function that looks like this:
i = 1
m(x) = 1 + a(i)*(x-b(i)) + a(i+1)*(x-b(i+1)) + a(i+2)*(x-b(i+2)) + ... + a(5)*(x-b(5))
I must integrate m(x) further in my code. I can't seem to find a way to build a loop for an inline function that kind of "builds itself" according to the size of other vectors.
Is there a way to do this?
Thanks!

Antworten (1)

Andrei Bobrov
Andrei Bobrov am 8 Sep. 2018
Bearbeitet: Andrei Bobrov am 9 Sep. 2018
m = @(x)1+a(:).'*(x - b(:))
use
>> a = [1 2 3 4 5];
b = [6 7 8 9 10];
m = @(x)1+a(:).'*(x - b(:));
m(4)
ans =
-69
>>
  2 Kommentare
Rafael Pereira de Resende Freitas
Andrei, thanks for your answer.
What does the ' do? Is there a way to check if my equation was fully mounted properly? I need to be sure that it's in the right form so that the integral does the right thing afterwards.
Walter Roberson
Walter Roberson am 8 Sep. 2018
Bearbeitet: Walter Roberson am 9 Sep. 2018
It is .' (transpose) not ' (conjugate transpose)
It appears to me that 1 should be added to the output. (Andrei has now fixed this in his post.)
After adding the 1 I can read off the math as being algebraically correct. However, the order of addition for the * function is not specified, so since you are using floating point, it is possible that the output would not be bitwise identical to what you would get from the formula you wrote out.
Using inline functions has been recommended against for more than a decade. No tools are available for building them up piecewise in an efficient form.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Function Creation finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by