Search code examples
stringmatlabdifferencestrcmpset-difference

How to display the differing elements in two string arrays in a loop?


I have two string arrays - f and g. I want the program to print the members of g that do not exist in f.

I have the following code:

% <for ... >
  % <get `f` and `g` as inputs>
  ...
  x = 0;
  y = 0;
  while x < a
    while y < b
      w = string(f);
      z = string(g);
      tf = strcmp(w,z);
      for tf == 0 %         < < < < < Help needed with this
        fprintf('%s\n',z)
      end
      y = y+1;
    end
    x = x+1;
  end
% end

The result I get for tf looks like 1 0 0. What I want is for the fprintf to display the entries that correspond to 0's in z (to display the differing members of w and z), how do I do that?


Solution

  • Here is a small code showing how to accomplish that:

    y = '12';
    x = 'hello 123';
    
    % First, check if the content of y is present in x
    temp = contains(x, y);
    if temp == 1 % x contains y
        disp ('x contains y');
    else
       disp ('X does not contain y'); 
    
    end
    
    % Second, replace y characters with nothing.
    % Result: Only characters not present in y will remain
    % for more information type 'docs strrep'
    temp2 =  strrep(x,y,'');
    disp (['Characters of x not in y: ' temp2])
    

    You will see:

    x contains y

    Characters of x not in y:hello 3