Search code examples
matlabcell-arraystrcmp

MatLab - Cellfun where func = strcmp Find where str changes in a cell array


I have a cell array of strings, I want to detect the num of times the string changes and get the indxs for the changes. Given Matlab's cellfun function, I am trying to use it instead of looping. Here is all the code. I appreciate you time, feedback, and comments.

% Cell Array Example
names(1:10)={'OFF'};
names(11:15)={'J1 - 1'};
names(16:22)={'J1 - 2'};
names(23:27)={'J2 - 1'};
names(28)={'Off'};
names=names';

% My cellfun code
cellfun(@(x,y) strcmp(x,y), names(1:2:end),names(2:2:end));

My expected result is a vector of length 27 (length(names)-1), where there are 4 zeros in the vector indicating the strcmp func found 4 cases where the comparison was not equal.

The actual result is a vector of length 14 and has only 2 zeros. I'd really appreciate an explanation, why this unexpected result is occurring.

Thank You


Solution

  • The answer provided by Matt correctly shows the issue with your code. However, you can use strcmp directly because it accepts two cell array of strings as input

    >> strcmp(names(1:end-1), names(2:end))
    ans =
      Columns 1 through 14
         1     1     1     1     1     1     1     1     1     0     1     1     1     1
      Columns 15 through 27
         0     1     1     1     1     1     1     0     1     1     1     1     0