Dynamic inline formula variable population

1 view (last 30 days)
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 Comment
Jeff
Jeff on 16 Dec 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

Sign in to comment.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 13 Dec 2012
Edited: Andrei Bobrov on 13 Dec 2012
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 Comments
Jeff
Jeff on 13 Dec 2012
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);

Sign in to comment.

More Answers (0)

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!