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!

답변 (1개)

Andrei Bobrov
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
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 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 CenterFile Exchange에서 Function Creation에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by