How do I create a loop to increment the number of terms of a function?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Rafael Pereira de Resende Freitas
el 8 de Sept. de 2018
Editada: Walter Roberson
el 9 de Sept. de 2018
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 comentarios
Respuestas (1)
Andrei Bobrov
el 8 de Sept. de 2018
Editada: Andrei Bobrov
el 9 de Sept. de 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 comentarios
Walter Roberson
el 8 de Sept. de 2018
Editada: Walter Roberson
el 9 de Sept. de 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.
Ver también
Categorías
Más información sobre Function Creation en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!