Search code examples
matlabsymbolssymbolic-mathsolver

Replace numeric values with symbols in an array


The problem I'm facing is the following: I have been given an array of 6x1 which includes 2 NaN that represent 2 unknown values. What I want to do is replace these values with symbolic values (ie. x_1 and x_2 for example). What I don't understand what to do is if i'm given a 12x1 array for example with 10 NaN which I would have to change to X_1, X_2...X_10 in order to use the solver afterwards.

array = [0; 0; NaN; 0; 0; 0; 0; NaN; 0];

Change into:

array = [0; 0; x_1; 0; 0; 0; 0; x_2; 0];

But it has to be a general solution for arrays with different NaN's.

Thanks a lot in advance for your help and time.


Solution

  • You can use the sym function:

    array=sym(array);
    array(isnan(array))=sym('x_',[sum(isnan(array)),1])
    

    Explanation: The first line converts the array to a symbolic array. The second replaces the Nan elements with numerically indexed symbolic variables created by the sym function.