2

I have 2 cell arrays as below:

A = {'S' 'M' 'N' 'E'};
B = {'E' 'M' 'Q' 'S'};

In this case, the number of different elements is 3.

In a number array, I can use length(find(A ~= B)); to easily count number of different elements in one step easily.

Is there something similar for cell array of characters?

0

4 Answers 4

2

EDIT: I think I've misunderstood your question, and you probably meant finding different elements in corresponding positions in the arrays. I still kept my old answer

Counting different elements at the same position

yuk's approach with strcmp is correct. However, it works only if the two arrays are of the same size. The generalized solution would be:

N = min(numel(A), numel(B));
sum(~strcmp(A(1:N), B(1:N))) + numel(A) + numel(B) - 2 * N

If the arrays are of different length, the "extra" elements in the larger array will be counted as different here.

Counting different elements in any position

The most general approach would be using ismember, which does not care about lengths of strings or their position in the array. To count the total number of elements in A and B that are different, just do:

sum(ismember(A, B)) + sum(ismember(B, A))

The same effect can also be obtained with setdiff (instead of ismember):

numel(setdiff(A, B)) + numel(setdiff(B, A))

Both ways are valid for any two arrays, not necessarily of equal size.

Sign up to request clarification or add additional context in comments.

Comments

2

Try

cell2mat(A)==cell2mat(B)

to start with, the rest should be straightforward. This simple approach will fail if the cell arrays don't have the same dimensions.

3 Comments

length(find(A ~= B)); would also fail if A and B have different number of elements so this sounds like the correct approach to me. +1
Yep, it works as expected, although I need to modify it a bit to use ~= since I want to find difference
This will work only if all strings in A and B are single-character.
2

If your cell array is a cell array of strings you can use STRCMP:

sum(~strcmp(A,B))

Of course make sure A and B have the same length.


By the way for numeric array it's more efficient to use sum(A~=B). In general find is slow.

Comments

0

U can also try unique([A B]) if A and B are given in the exemple you gave. It A and B do not have the same dimension you can try this.

unique(reshape(cell2mat(A,1,[])),reshape(cell2mat(B,1,[])))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.