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

Jeff
Jeff 2012년 12월 16일
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

댓글을 달려면 로그인하십시오.

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 12월 13일
편집: Andrei Bobrov 2012년 12월 13일

0 개 추천

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

Jeff
Jeff 2012년 12월 13일
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 2012년 12월 13일
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);

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Function Creation에 대해 자세히 알아보기

제품

질문:

2012년 12월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by