Dynamic inline formula variable population

Hello,
I created an object that accepts a formula (i.e. Tranfunction ='a.*b.*c') and a matrix of values ( i.e. Mat = [ 1 2 3; 4 5 6; 7 8 9] ). Once these variable and Matrix have been loaded into the object the following code is applied.
fun = inline(obj.TranFunction);
NewMatrix = fun(Mat(:,1), Mat(:,2), Mat(:,3));
This works great.
However, the Tranfunction can be enter as anything (i.e. tranfunction = '(12.*e.*d.*c)./ ((4.*a.^3)-(3.*b.*(2.*pi.*a.^2+pi.*b.^2+8.*a.*b)) + (12.*(a+b).^2))' and the corresponding matrix( i.e. Mat = [ 1 2 3 4 5; 4 5 6 6 7; 7 8 9 9 9] )
When this happens I have to change my code to:
fun = inline(obj.TranFunction);
NewMatrix = fun(Mat(:,1), Mat(:,2), Mat(:,3), Mat(:,4), Mat(:,5));
Is there a way that I can make the NewMatrix line of code dynamic? A piece of code that wouldn't require me to change the NewMatrix line every time the forumla changes?
Thanks for your help,
Jeff

1 Kommentar

Jeff
Jeff am 16 Dez. 2012
I was able to solve it by using regexprep to replace the letters in the formula with the appropriate vectors. Then use the eval function to solve the new formula.
Its seems that most people don't like the eval function, but it works well for me.
Thanks,
Jeff

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 13 Dez. 2012
Bearbeitet: Andrei Bobrov am 13 Dez. 2012

0 Stimmen

Tranfunction = 'prod(Ain,2)';
fun = inline(obj.TranFunction);
NewMatrix = fun(Mat);
ADD
Tranfunction = '(12.*prod(m(:,[3:end]),2))./ ((4.*m(:,1).^3)-(3.*m(:,2).*(2.*pi.*m(:,1).^2+pi.*m(:,2).^2+8.*m(:,1).*m(:,2))) + (12.*(m(:,1)+m(:,2)).^2))';
fun = inline(obj.TranFunction);
NewMatrix = fun(m);

3 Kommentare

Jeff
Jeff am 13 Dez. 2012
Andrei,
I'm sorry I simplified the Tranfunction to much making it seem like I am always multiplying them. Here is a real world example I recently used.
Tranfunction = (12.*e.*d.*c)./ ((4.*a.^3)-(3.*b.*(2.*pi.*a.^2+pi.*b.^2+8.*a.*b)) + (12.*(a+b).^2))'
So you can't simply use the prod syntax.
Thanks,
Jeff
Andrei Bobrov
Andrei Bobrov am 13 Dez. 2012
see ADD
Andrei,
I tried your approach and got an error. This way will work for me, any ideas? See below...
>> mat = magic(3)
mat =
8 1 6
3 5 7
4 9 2
>> f = inline('mat(:,1).*mat(:,2).*mat(:,3)')
f =
Inline function:
f(x) = mat(:,1).*mat(:,2).*mat(:,3)
>> f(mat)
??? Error using ==> inlineeval at 15 Error in inline expression ==> mat(:,1).*mat(:,2).*mat(:,3) Undefined function or variable "mat".
Error in ==> inline.subsref at 27 INLINE_OUT_ = inlineeval(INLINE_INPUTS_, INLINE_OBJ_.inputExpr, INLINE_OBJ_.expr);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Function Creation finden Sie in Hilfe-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