toString function (trying to write a function that takes a cell array expression and returns a string)
조회 수: 1 (최근 30일)
이전 댓글 표시
How do I write a toStringfunction that takes any cell array expression and returns a human-readable string. I need to do this for addition, subtraction, multiplication, division, a number, negation, powers, square roots, and variables. I have the first 4 done but can't seem to figure out the rest. This is what I have so far:
function s = toString(Expr)
type = Expr{1};
switch type
case {'Add'}
% the expression looks like {'Add', ___, ___}
Arg1 = Expr{2};
Arg2 = Expr{3};
s = [toString(Arg1) ' + ' toString(Arg2)];
case {'Sub'}
Arg1 = Expr{2};
Arg2 = Expr{3};
s = [toString(Arg1) ' - ' toString(Arg2)];
case {'Mul'}
Arg1 = Expr{2};
Arg2 = Expr{3};
s = [toString(Arg1) ' * ' toString(Arg2)];
case {'Div'}
Arg1 = Expr{2};
Arg2 = Expr{3};
s = [toString(Arg1) ' / ' toString(Arg2)];
case {'Num'}
Arg1 = Expr{2};
s = [numtostr(Arg1)];
case {'Neg'}
Arg1 = Expr{2};
s = [ '-' toString(Arg1)];
case {'Pow'}
Arg1 = Expr{2};
Arg2 = Expr{3};
s = [toString(Arg1) ' ^ ' toString(Arg2)];
case {'Sqrt'}
Arg1 = Expr{2};
s = [toString(Arg1) '^(1/2)'];
case {'Var'}
Arg1 = Expr{2};
s = [toString(Arg1)];
end
end
댓글 수: 0
답변 (2개)
Clemens
2011년 4월 22일
looks you are nearly done.
All I notice is that you always call the toString in all cases but the one with 'Num'. This means in the case 'Var' never a string is created.
You could do this simple by adding:
if ischar(Expr)
s = Expr;
return
end
to the beginning. Or maybe in the case 'Var' by not using the toString function - like you did in the 'Num' case.
On a related note - if you plan to create more complicated expressions it might be usefull to add brackets to the strings.
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!