how to retrieve numbers from symbol?

6 views (last 30 days)
Hi all,
Suppose I have defined
syms x1 x2 x45;
I want to detect and retrieve the numbers 1, 2, 45 from x1, x2, x45. Is that possible in matlab?
Thank you.

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 13 Dec 2013
Edited: Azzi Abdelmalek on 13 Dec 2013
syms x1 x2 x45;
str2double(regexp(char(x45),'\d','match'))

More Answers (1)

Walter Roberson
Walter Roberson on 13 Dec 2013
I am not sure what benefit there would be to that? It is bad practice to encode information into variable names and later to pull apart the variable names and use the information.
Are you trying to convert x1 x2 x45 to x(1), x(2), x(45) for the purpose of converting a list of individual variable names into an indexed vector? e.g., if you were doing a minimization of something defined in 45 variables x1 x2 up to x45 that had been converted with matlabFunction() would normally end up as a function of 45 variables in the argument list, but the minimizers would instead want to pass in a vector with 45 values. Is that the situation you are facing? If it is, then there is a way to get matlabFunction to generate the function header a form suitable for passing in a vector instead.
matlabFunction( ...., 'vars', [x1 x2 x3 ... x45])
notice the [] around the list. When you use [] then MATLAB will generate a single name that group of parameters and will index that name to provide the individual parameters, along the lines of
function r = function(X)
x1 = X(:,1); x2 = X(:,2); x3 = X(:,3); .... x45 = X(:,45);
  2 Comments
Marrie
Marrie on 13 Dec 2013
Hi Walter,
Thank you very much for the detailed answer.
The problem I am facing now is to compute the jacobian of a vector, which has 10000 elements and it is very time-consuming.
Considering the sparsity of my jacobian, I want to compute the derivatives of non-zeros only. The first step is to determine the locations of those non-zeros, that is to find the dependence of the vector function on the variables.
For example, if I define the vector function f(x1,x2,...,x1000) and the jth component takes the form fj=x1+(x45+1)*x2, thus J(j,1), J(j,2) and J(j,45) are non-zeros. I am using symvar(fj) to retrieve these symbols, but I need the indices of the variables too.
Walter Roberson
Walter Roberson on 13 Dec 2013
Are functions multinomials like you illustrate with? Each term being of the form c * v1^n * v2^m * v3^... with "c" a constant, v* the variables, and n, m, etc. being non-negative integers? If so then you can use coeffs() at the MATLAB level, or you can use evalin() or feval() to invoke MuPAD's coeff() function; I suggest you look at the latter http://www.mathworks.com/help/symbolic/mupad_ref/coeff.html

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!