How to compare the contents of two tables?
조회 수: 26 (최근 30일)
이전 댓글 표시
I have two tables to compare. One is from this month (Feb.) and the other from the previous month (Jan.)
tab_jan =
Country ID Name Technology Status x_OfTechnology Capacity
_______ ____ ____ __________ ______ ______________ ________
'AAA' 1001 'a' 'BB' 'C1' 1 10
'AAA' 1002 'b' 'AA' 'C1' 4 24
'AAA' 1003 'c' 'BB' 'C2' 5 30
'AAA' 1004 'd' 'AA' 'C3' 4 20
'AAA' 1005 'e' 'AA' 'C4' 10 35
'AAA' 1006 'f' 'AA' 'C5' 8 40
tab_feb =
Country ID Name Technology Status x_OfTechnology Capacity
_______ ____ ____ __________ ______ ______________ ________
'AAA' 1008 'h' 'CC' 'C1' 1 2
'AAA' 1007 'g' 'AA' 'C1' 3 9
'AAA' 1001 'a' 'BB' 'C2' 1 10
'AAA' 1003 'c' 'BB' 'C2' 4 24
'AAA' 1004 'd' 'AA' 'C3' 4 20
'AAA' 1005 'e' 'AA' 'C4' 10 35
'AAA' 1006 'f' 'AA' 'C5' 8 40
Compared to January, on February following things happened:
- Project a (ID: 1001) moved up to C2
- Project b (ID: 1002) got deleted
- Project c (ID: 1003) capacity decreased due to drecrease in number of technology
- Project g (ID: 1007) got added as a new C1 project
- Project h (ID: 1008) got added as a new C1 project and as a new Technology CC
How may I proceed with the comparison of the presented tables to obtain the list of changes as the result?
댓글 수: 0
채택된 답변
Voss
2022년 3월 23일
Here is something that will print changes in the tables to the command-line:
tab_jan = readtable('jan.csv');
tab_feb = readtable('feb.csv');
% deleted projects:
[is_extant,idx_in_feb] = ismember(tab_jan.ID,tab_feb.ID);
if any(~is_extant)
fprintf('Projects Deleted between Jan and Feb:\n');
disp(tab_jan(~is_extant,:));
fprintf('\n');
end
% newly added projects:
added_idx = ~ismember(tab_feb.ID,tab_jan.ID);
if any(added_idx)
fprintf('Projects Added between Jan and Feb:\n');
disp(tab_feb(added_idx,:));
fprintf('\n');
end
% changed projects:
no_changes = true;
props = tab_jan.Properties.VariableNames;
format_prefix = 'Project %s (ID: %d) ''%s'' changed: ';
for ii = 1:height(tab_jan)
if ~is_extant(ii)
continue
end
args = {tab_jan{ii,'Name'}{1},tab_jan{ii,'ID'},[],[],[]};
for jj = 1:numel(props)
if isequal(tab_jan{ii,jj},tab_feb{idx_in_feb(ii),jj})
continue
end
args(3:5) = { ...
props{jj}, ...
tab_jan{ii,jj}, ...
tab_feb{idx_in_feb(ii),jj} ...
};
if iscell(tab_jan{ii,jj})
args{4} = args{4}{1};
args{5} = args{5}{1};
my_format = [format_prefix '%s -> %s\n'];
else
my_format = [format_prefix '%d -> %d\n'];
end
if no_changes
fprintf('Projects Changed between Jan and Feb:\n');
no_changes = false;
end
fprintf(my_format,args{:});
end
end
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Tables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!