www.gusucode.com > mbctools 工具箱 matlab 源码程序 > mbctools/@sweepset/align.m
function [out, OK, msg] = align(originalSS, newSS, commonVariables) %ALIGN Align sweepsets % % [SS, OK, MSG] = ALIGN(SS1, SS2, VARS) % Copyright 2000-2015 The MathWorks, Inc. and Ford Global Technologies, Inc. if nargin<3 commonVariables = intersect(get(originalSS, 'Name'), get(newSS, 'Name')); end OK = 0; out = sweepset; msg = ''; if isempty(commonVariables) && size(originalSS,1)==size(newSS,1) % no variables in common and same size so just concatenate out = [originalSS,newSS]; OK = true; elseif isempty(find(originalSS, commonVariables)) || isempty(find(newSS, commonVariables)) % ss1 and ss2 contain variables vars? OK = false; msg = 'Requested variables not found in both sets of data'; else % First, is alignment possible? i.e. does vars uniquely identify a record S = substruct('()',{':' commonVariables}); alignSS1 = subsref(originalSS, S); alignSS2 = subsref(newSS, S); [sortSS1, index1] = sortrows(alignSS1.data); [sortSS2, index2] = sortrows(alignSS2.data); % Note: sortSS1 = SS1(index1) but we want SS1 = sortSS1(invIndex1) [~, invIndex1] = sort(index1); % NaN's are put at end of sort. So any NaN's will be in last row. NaN fails at intersect if any(isnan(sortSS1(end,:))) || any(isnan(sortSS2(end,:))) msg = 'Alignment is not possible on data sets that include NaN''s or bad data'; return end % Is SS1 uniquely identified by the suggested variables if size(sortSS1, 1) ~= size(unique(sortSS1, 'rows'), 1) msg = 'Record alignment cannot be unique with selected variables'; return end % Find the intersection of these two sorted datasets. % NOTE: C = sortSS1(ind1) & C = sortSS2(ind2) [C, ~, ind2] = intersect(sortSS1, sortSS2, 'rows'); % Did we find a matching partner for everyone in sortSS1? if ~isequal(C, sortSS1) msg = ['Only ' num2str(size(C, 1)) ' matching records found in the data being aligned']; return end % Is SS2 also unique in the selected variables. % i.e. are there duplicates in SS2 which match SS1 dupSS2 = sum(diff(sortSS2, 1, 1), 2) == 0; if any(dupSS2) C = intersect(sortSS2(dupSS2), sortSS1, 'rows'); if ~isempty(C) msg = 'Data to be aligned cannot be uniquely identified with selected variables'; return end end % Now we know there is a one-to-one mapping between the variables vars in SS1 and SS2 % So map SS2 onto SS1 in the correct order. index = index2(ind2(invIndex1)); [~, indexVarsToAppend] = setdiff(get(newSS, 'Name'), get(originalSS, 'Name')); if ~isempty(indexVarsToAppend) % Now append all variables from SS2 to SS1 S = substruct('()', {index, indexVarsToAppend, ':'}); out = [originalSS subsref(newSS, S)]; OK = true; else msg = 'No new variables to merge'; OK = false; end end