如何获得字符串形式的方程式?
How do I get an equation as a string?
我有一个方程用于制作等值面,然后将其保存到文件中,我需要跟踪哪些方程属于哪个文件。因此,我想用生成它们的等式标记我的 Octave 脚本生成的文件,而不用手动标记它们。
这是我现在的代码:
clf;
function [f, v] = doiso(dodraw)
m = 3;
dim = -m:0.1:m;
if (dodraw > 0)
dim = -m:0.6:m;
endif
[x,y,z] = meshgrid(dim, dim, dim);
func = cos(x) .* sin(y) + cos(y) .* sin(z) + cos(z) .* sin(x);
if (dodraw > 0)
isosurface(func, 0);
else
[f, v] = isosurface(func, 0);
endif
endfunction
#draw
doiso(1);
axis equal;
title("isosurface() of the function");
#saveq
[f, v] = doiso(0);
vertface2obj(v, f, strcat("objs/", int2str(time * 1000), "out.obj"));
保存的文件的名称应类似于 cos(x) . sin(y) + cos(y) . sin(z) + cos(z) . sin(x) 1513441860368.obj
,其中长数字是时间戳,包含 sin 和 cos 的表达式是生成文件的方程式(与代码中的相同)。必须删除或替换文件名字符串中的无效字符。
似乎没有在线资源提及打印方程式;仅打印数字或求解方程式。
一种方法是使用 func2str()
:
func2str (fcn_handle)
Return a string containing the name of the function referenced by the function handle fcn_handle
.
您必须为您的方程创建一个匿名函数。例如,
> f = @(x,y,z) cos(x) .* sin(y) + cos(y) .* sin(z) + cos(z) .* sin(x);
> eqn = func2str(f);
> fprintf(stdout, '%s\n', eqn)
@(x, y, z) cos (x) .* sin (y) + cos (y) .* sin (z) + cos (z) .* sin (x)
如您所见,上面的代码创建了字符串 eqn
,其中包含函数 f
的表达式。
然后您可以操作该字符串以获得更合理的文件名。这是一个简单的例子:
> fname = regexprep(strjoin(strsplit(eqn(11:end)), ''), '[().*+]', '_')
fname = cos_x___sin_y__cos_y___sin_z__cos_z___sin_x_
此处 strjoin(strsplit(str), '')
删除字符串 str
中的所有空格。函数 regexprep()
使用正则表达式替换将 "undesired" 字符替换为下划线。
您当然可以进行更精细的操作,例如将 *
更改为 _TIMES_
或您喜欢的任何内容。
更多关于操作字符串 here.
我有一个方程用于制作等值面,然后将其保存到文件中,我需要跟踪哪些方程属于哪个文件。因此,我想用生成它们的等式标记我的 Octave 脚本生成的文件,而不用手动标记它们。 这是我现在的代码:
clf;
function [f, v] = doiso(dodraw)
m = 3;
dim = -m:0.1:m;
if (dodraw > 0)
dim = -m:0.6:m;
endif
[x,y,z] = meshgrid(dim, dim, dim);
func = cos(x) .* sin(y) + cos(y) .* sin(z) + cos(z) .* sin(x);
if (dodraw > 0)
isosurface(func, 0);
else
[f, v] = isosurface(func, 0);
endif
endfunction
#draw
doiso(1);
axis equal;
title("isosurface() of the function");
#saveq
[f, v] = doiso(0);
vertface2obj(v, f, strcat("objs/", int2str(time * 1000), "out.obj"));
保存的文件的名称应类似于 cos(x) . sin(y) + cos(y) . sin(z) + cos(z) . sin(x) 1513441860368.obj
,其中长数字是时间戳,包含 sin 和 cos 的表达式是生成文件的方程式(与代码中的相同)。必须删除或替换文件名字符串中的无效字符。
似乎没有在线资源提及打印方程式;仅打印数字或求解方程式。
一种方法是使用 func2str()
:
func2str (fcn_handle)
Return a string containing the name of the function referenced by the function handle
fcn_handle
.
您必须为您的方程创建一个匿名函数。例如,
> f = @(x,y,z) cos(x) .* sin(y) + cos(y) .* sin(z) + cos(z) .* sin(x);
> eqn = func2str(f);
> fprintf(stdout, '%s\n', eqn)
@(x, y, z) cos (x) .* sin (y) + cos (y) .* sin (z) + cos (z) .* sin (x)
如您所见,上面的代码创建了字符串 eqn
,其中包含函数 f
的表达式。
然后您可以操作该字符串以获得更合理的文件名。这是一个简单的例子:
> fname = regexprep(strjoin(strsplit(eqn(11:end)), ''), '[().*+]', '_')
fname = cos_x___sin_y__cos_y___sin_z__cos_z___sin_x_
此处 strjoin(strsplit(str), '')
删除字符串 str
中的所有空格。函数 regexprep()
使用正则表达式替换将 "undesired" 字符替换为下划线。
您当然可以进行更精细的操作,例如将 *
更改为 _TIMES_
或您喜欢的任何内容。
更多关于操作字符串 here.