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!