MATLAB: How to recognize multiplication with out *

multiply function polynomial solve string

I want to write a code where you can input a string of a polynomial for instance '2x+3' and matlab returns the string as '2*x+3'. The user can input any string of a polynomial and matlab adds the * where needed.
I was thinking of possibly using a for loop (length of the string) where it passes through each indices and use isletter or isnumeric and if I get a numeric followed by a letter The code addes a * in between.
Can someone help me implement this or have a better way of doing so. Thanks a lot!

Best Answer

  • Brute force loop:
    s = '2x + 3 - 5y';
    isdigit = @(x)(x>='0'&x<='9');
    s(s==' ') = []; % if you want to protect against blanks
    n = numel(s);
    t = s(1);
    for k=2:n
    if( isdigit(s(k-1)) && isletter(s(k)) )
    t = [t '*'];
    t = [t s(k)];
    t =
    There are ways to vectorize this and not increase the size of t in a loop, but for the small string size you will likely be dealing with it is hardly worth the effort.