Hello,
I need a modified eval function. For example, I have in my workspace :
Nx = 3;
mystring = '1+2*Nx';
is_string = false; % treat it as matlab code
is_string2 = true; % treat it as text
I want to run the following lines :
if is_string, out = mystring,
else out = eval(mystring),
end
if is_string2, out2 = mystring,
else out2 = eval(mystring),
end
I am looking for a way to put this in a function :
Nx = 3;
mystring = '1+2*Nx'
is_string = false; % treat it as matlab code
is_string2 = true; % treat it as text
out = my_eval(mystring,is_string) % returns 7
out2 =my_eval(mystring,is_string2) % returns '1+2*Nx'
Anybody knows how to do this ?
Thanks

 채택된 답변

dpb
dpb 2014년 8월 13일

0 개 추천

function out=my_eval(in,isStr)
if isStr
out=in;
else
out=evalin('caller',in);
end
doc evalin % for details/limitations
Might also consider using function handles and, perhaps creating dynamically an anonymous function handle which is then evaluted...depends on the end use.

댓글 수: 1

Arnaud
Arnaud 2014년 8월 13일
Thanks ! Obviously I should have looked at the end of the eval function to find this evalin function !

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

추가 답변 (1개)

Adam
Adam 2014년 8월 13일

0 개 추천

I would define as follows:
Nx = 3;
myFunc = @() 1 + 2*Nx
then
out = my_eval( myFunc, is_string )
would contain something like:
if is_string
out = strrep( func2str( myFunc ), '@()', '' )
else
out = myFunc();
end

댓글 수: 1

Arnaud
Arnaud 2014년 8월 13일
편집: Arnaud 2014년 8월 13일
Thanks but I'd rather not modify my string.

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

카테고리

도움말 센터File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

질문:

2014년 8월 13일

편집:

2014년 8월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by