Convert output of symbolic factorization to matrix representation in Matlab

Output

factor (SYM ('12345678901234567890'))

is an

ans =

2*3^2*5*101*3541*3607*3803*27961

      

Is there an easy way to change the output to something like:

[2 3 5 101 3541 3607 3803 27961; 1 2 1 1 1 1 1 1]?

      

+3


source to share


1 answer


Try this code:

aux = char(factor(sym('12345678901234567890'))); % convert to string
aux = regexprep(aux, {'*'}, ''',''');            % replace '*' with '',''
result = eval( ['{''',aux,'''}']);               % evaluate string expression

% Separate each string into tokens around the '\^' character
factor = cell(1,length(result));
exponent = cell(1,length(result));
for i=1:length(result)
    factor{i} = regexpi(result{i}, '(\w*)\^', 'tokens');
    if isempty(factor{i})
        factor{i} = result{i};
    else
        factor{i} = char(factor{i}{1});
    end
    exponent{i} = regexpi(result{i}, '\^(\w*)', 'tokens');
    if isempty(exponent{i})
        exponent{i} = '1';
    else
        exponent{i} = char(exponent{i}{1});
    end
end

% Converting the cellstr to normal matrices
factors = zeros(length(factor),1);
exponents = zeros(length(exponent),1);
for i=1:length(factor)
    factors(i) = str2num(factor{i});
    exponents(i) = str2num(exponent{i});
end

clear result factor exponent i aux;

      



In fact, the solution is similar to Coqbira's proposal.

Hope it helps,

+1


source







All Articles