How do I create a loop to increment the number of terms of a function?
2 views (last 30 days)
Show older comments
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!
0 Comments
Answers (1)
Andrei Bobrov
on 8 Sep 2018
Edited: Andrei Bobrov
on 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 Comments
Walter Roberson
on 8 Sep 2018
Edited: Walter Roberson
on 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.
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!