Concatenate and sort 2 Matrices containing intervals
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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?
1 Kommentar
Antworten (1)
Guillaume
am 29 Aug. 2016
Bearbeitet: Guillaume
am 29 Aug. 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 Kommentare
Siehe auch
Kategorien
Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!