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!