Problem with "Intersect" function

17 views (last 30 days)
pradeep kumar
pradeep kumar on 22 Jun 2017
Edited: Jan on 22 Jun 2017
Hellow everyone! I have 2 cells.
A = '1,2,3';
B= '1,4,5,6';
But, When i try to use intersect function to get the common element(s) as my result, say
C = intersect(A, B);
I am getting an empty cell like this.
C =
Empty cell array: 1-by-0
Kindly help me, My result shall show like
Your help will be highly appreciated!
pradeep kumar
pradeep kumar on 22 Jun 2017
@ Alice! Yes, A & B are different cells and contain strings. Please tell me how can i break them to individual number (or strings) to get my job done.
pradeep kumar
pradeep kumar on 22 Jun 2017
@ Stephen Cobeldick , You mean to say my cells should look like the following .
Kindly tell me, how can i achieve this?

Sign in to comment.

Accepted Answer

Jan on 22 Jun 2017
Edited: Jan on 22 Jun 2017
But the shown code works:
A = '1,2,3';
B = '1,4,5,6';
C = intersect(A, B);
% C = ',1' % The commonly appearing characters ',' and '1'
According to the posted code, A and B are not cells, but char vectors, also called strings.
If you want to treat the numbers as numbers:
An = sscanf(A, '%g,');
Bn = sscanf(B, '%g,');
Cn = intersect(An, Bn)
% C = 1
If A and B are cells, use "A{1}" and "B{1}" instead.
It depends on your specific problem if the input data should be
A = {'1','2','3'};
A = [1,2,3]
Most likely you do not have to convert the cell string {'1,2,3'}, if you choose the rigth method to obtain the data at the beginning. Where do these data come from?

More Answers (1)

KSSV on 22 Jun 2017
A = [1,2,3] ;
B = [1,4,5,6];
A = '1,2,3';
B= '1,4,5,6';
  1 Comment
pradeep kumar
pradeep kumar on 22 Jun 2017
@ KSSV, str2num doesn't work, since A and B are 2 cells. It shows the following error.
Error using str2num (line 32)
Requires string or character array input.
Kindly help me.

Sign in to comment.


Find more on Characters and Strings in Help Center and File Exchange


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!