Reputation: 7
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
Upvotes: 0
Views: 2679
Reputation: 112749
You could transform the strings into numeric labels using unique
, and then apply diff
to detect changes:
[~, ~, u] = unique(names);
result = ~diff(u);
Upvotes: 2
Reputation: 9864
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
Upvotes: 3
Reputation: 4049
If I understand your question correctly, you should be comparing names(1:end-1)
with names(2:end)
. That is, compare string 1 with string 2, compare string 2 with string 3, and so on. You are instead using a stride of 2, comparing string 1 with string 2, string 3 with string 4, and so on. You can fix this by changing your last line to:
cellfun(@(x,y) strcmp(x,y), names(1:end-1),names(2:end))
The result is then:
Columns 1 through 20:
1 1 1 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1
Columns 21 through 27:
1 0 1 1 1 1 0
Upvotes: 0