Compare two columns having different values.

I have 2 variables A and B, I want to compare the values with each other and want result like variable C. Is there any direct function I can use to get C?
A={'a','b','c','d','e'}
B={'b','c','d','e','f'}
C={'a',-
'b','b'
'c','c'
'd','d'
'e','e'
-.'f'}

Answers (2)

try this:
A={'a','b','c','d','e'};
B={'b','c','d','e','f'};
C={'a','-'
'b','b'
'c','c'
'd','d'
'e','e'
'-.','f'};
a=[A(2:end) B(1:end-1)]';
b=[[A(1) '-'];reshape(a,[],2)];
out=[b;['-.' B(end)]]
out = 6×2 cell array
{'a' } {'-'} {'b' } {'b'} {'c' } {'c'} {'d' } {'d'} {'e' } {'e'} {'-.'} {'f'}

4 Comments

MakM
MakM on 28 Mar 2022
Edited: MakM on 28 Mar 2022
Thanks for the answer Arif, thats some kind of hard code, Do you know how can we do it with a function, like compare the values and get output.
you can use horzcat and vertcat function
A={'a','b','c','d','e'};
B={'b','c','d','e','f'};
C={'a','-'
'b','b'
'c','c'
'd','d'
'e','e'
'-.','f'};
a=transpose(horzcat(A(2:end),B(1:end-1)));
b=vertcat(horzcat(A(1),'-'),reshape(a,[],2));
out=vertcat(b,horzcat('-.',B(end)))
The main idea is to compare the A and B and then get the answer, not to get the answer by hard coding.
I hope u hv understand my question :)
A={'a','b','c','d','e'};
B={'b','c','d','e','f'};
for i=1:length(A)
for j=1:length(B)
if any(strcmp(A(i),B(j)))==1
C(i,:)=[A(i) B(j)];
end
end
end
output=[A(1) '-';C(2:end,:);'-.' B(end)]
output = 6×2 cell array
{'a' } {'-'} {'b' } {'b'} {'c' } {'c'} {'d' } {'d'} {'e' } {'e'} {'-.'} {'f'}

Sign in to comment.

I will suggest the table join to do it:
tbla=table;
tblb=table;
tbla.var={'a','b','c','d','e'}';
tblb.var={'b','c','d','e','f'}';
tblc=outerjoin(tbla, tblb);
C=tblc{:,:};
C(cellfun(@isempty,C))={'-'};

Tags

Asked:

on 28 Mar 2022

Answered:

on 1 Apr 2022

Community Treasure Hunt

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

Start Hunting!