Concatenate and sort 2 Matrices containing intervals
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have 2 Matrices A and B that have to be concatenated and sorted in a way that C is the result for the given example
if true
A = [ 1 5 0.01 ; 5 10 0.02; 10 20 0.03];
B = [ 6 7 0.04 ; 9 15 0.05 ];
C = [1 5 0.01 ; 5 6 0.02; 6 7 0.04; 7 9 0.02; 9 15 0.05; 15 20 0.03];
end
A contains intervals and has to be extended by given intervals in B.
any suggestions?
Réponses (1)
Guillaume
le 29 Août 2016
Modifié(e) : Guillaume
le 29 Août 2016
Assuming that your intervals don't span too big of a range and that they're all on integer boundaries, you could expand both A and B into a list of integers and corresponding values, union the two together and transform the union back into intervals:
A = [ 1 5 0.01 ; 5 10 0.02; 10 20 0.03];
B = [ 6 7 0.04 ; 9 15 0.05 ];
%function to expand intervals
expandinterval= @(m) cell2mat(cellfun(@(row) [row(1):row(2)-1; repmat(row(3), 1, row(2)-row(1))], num2cell(m, 2)', 'UniformOutput', false));
expA = expandinterval(A);
expB = expandinterval(B);
%compute the union of the 1st row of the 2 sets.
%Don't use union as it makes it difficult to track where the elements come from
%instead use unique:
merged = [expB, expA]; %put B first so that it takes precedence over the same values in A
[expC, origcol] = unique(merged(1, :)); %union of 1st row
expC(2, :) = merged(2, origcol); %and corresponding 2nd row
%now compact back into intervals:
%I assume here that expC(1, :) is continuous as in your example, so we only have to deal with discontinuities in the 2nd row.
%If not, the code will have to be more complex
assert(all(diff(expC(1, :)) == 1), 'intervals are not continuous');
edges = find(diff(expC(2, :))); %find discontinuities in second row
C = [expC(1, [0, edges] + 1); expC(1, [edges, end]) + 1; expC(2, [0, edges] + 1)].'
0 commentaires
Voir également
Catégories
En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!