Compare two columns having different values.

조회 수: 1 (최근 30일)
MakM
MakM 2022년 3월 28일
답변: MJFcoNaN 2022년 4월 1일
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'}

답변 (2개)

Arif Hoq
Arif Hoq 2022년 3월 28일
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
MakM
MakM 2022년 3월 29일
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 :)
Arif Hoq
Arif Hoq 2022년 3월 29일
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'}

댓글을 달려면 로그인하십시오.


MJFcoNaN
MJFcoNaN 2022년 4월 1일
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))={'-'};

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by