MATLAB: Strings do not want to execute

executing stringsMATLAB

I am trying to execute this code:
function prep_data
str=input('Data to be Sorted:','s');
columize=sprintf('%s=%s(:)',str,str);
clean_neg=sprintf('%s=%s(%s>=0)',str,str,str);
clean_above_100=sprintf('%s=%s(%s<=100)',str,str,str);
eval(columize)
eval(clean_neg)
eval(clean_above_100)
At the prompt I enter the the name of the variable i want to alter. This program should take any 2 dimensional variable, move all of the data into one column, remove all negatives and remove all numbers above 100.
It is constructing the right strings however is having trouble executing them. Am I doing something wrong?

Best Answer

  • Yes, the EVAL-approach is the wrong idea already. Avoid EVAL in general. There is always a better solution.
    But at least an EVALIN is required in your case:
    function prep_data
    str = input('Data to be Sorted:', 's');
    V = evalin('base', str); % Obtain the value from the base workspace
    V = V(:); % actually not required
    V = V(V > 0 & V <= 100);
    assignin('base', str, V);
    But a much cleaner and safer approach would be:
    function V = prep_data(V)
    V = V(:);
    V = V(V > 0 & V <= 100);
    Then call this function as:
    <str> = prep_data(<str>)
    with the according name instead of "<str>". If you are indoubt if EVAL is good idea, search in this forum for this term.