将字符串转换为符号表达式,尊重工作空间

时间:2018-05-28 09:16:09

标签: matlab symbolic-math

Matlab可以将字符串转换为符号表达式,但在这里我希望根据工作空间中已知的值来解释字符串:

syms x y
y = x;
sym('x + y')  % depending on version, use "sym(", "str2sym(" or "evalin(symengine,"
ans =
x + y

如何编写x + x或2 * x的输出?

另一个例子:

syms x y
y = x;
z = sym('a + y')

如何修改代码以给出z = a + x?

基本问题似乎是sym(字符串)对过去一无所知(不考虑之前定义的内容)和未来(未将其变量声明为syms - 它怎么可能?)

我认为一个简单的表达式解析器可以做到这一点:检查字符串中的变量是否存在于工作空间中,如果不存在则将其声明为符号。

1 个答案:

答案 0 :(得分:0)

## Euclidian Distance  
        # Remember: 
        #1.|| a || = sqrt(aDOTa), 
        #2. d(x,y) = || x - y || = sqrt((x-y)DOT(x-y))
        #3. aDOTb = sum(a*b)


        d<-function(x,y){
                aux=x-y
                dis=sqrt(sum(aux*aux))
                return(dis)
        }

        ##Radial Basis Function Kernel
        # Remember :
        # 1.K(x,x')=exp(-q||x-x'||^2) where ||x-x'|| is could be defined as the
        # euclidian distance and 'q' it's the gamma parameter
        rbf<-function(x,y,q=0.2){
                aux<-d(x,y)
                rbfd<-exp(-q*(aux)^2)
                return(rbfd)
        }
        #
        #calculating the kernel matrix
        kernelmatrix=matrix(0,nrow(data),nrow(data))
        for(i in 1:nrow(data)){
                for(j in 1:nrow(data)){
                        kernelmatrix[i,j]=rbf(data[i,1:(ncol(data)-1)],data[j,1:(ncol(data)-1)],q)
                }
        }

上传到文件交换https://de.mathworks.com/matlabcentral/fileexchange/67519-str2syms-symstr-