How do I create a loop to increment the number of terms of a function?
2 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (1 件)
Andrei Bobrov
2018 年 9 月 8 日
編集済み: Andrei Bobrov
2018 年 9 月 9 日
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 件のコメント
Walter Roberson
2018 年 9 月 8 日
編集済み: Walter Roberson
2018 年 9 月 9 日
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.
参考
カテゴリ
Help Center および File Exchange で Function Creation についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!