Compare two arrays (intersection) and create new array with output columns, but with repetitions
Ältere Kommentare anzeigen
Hi,
I have following example arrays, and I want to write the values of the second array to a new array if the values of the first column intersect.
A = [1 3500; 2 100; 2 564; 3 2140; 3 9820; 2 8952]
B = [1 0 0 0.5; 2 0 0 0.8; 3 0 1 0; 4 0 1 0.5; 5 1 1 0; 6 1 1 0.5]
The output should look like this:
C = [0 0 0.5; 0 0 0.8; 0 0 0.8; 0 1 0; 0 1 0; 0 0 0.8]
I tried to use intersect, but it only returns with no repetition, ismember only returns logical and the position is irrelevant for me. And my workaround code does not rly give me what i like to have:
[~, rowsA, rowsB] = intersect(A(:, 1), B(:, 1));
C = [B(rowsB 2) B(rowsB, 3) B(rowsB, 4)];
% Code with ismember (workaround try)
v = intersect(B(:,1),A(:,1));
bmin = ismember(B(:,1),v(:,1));
bmax = ismember(A:,1),v(:,1));
imin = find(bmin);
imax = find(bmax);
S = B(imin);
T = A(imax);
Is there any workaround that I can use to create this output array?
Akzeptierte Antwort
Weitere Antworten (1)
the cyclist
am 17 Nov. 2019
It's a little convoluted, but this should work:
A = [1 3500, 2 100, 2 564, 3 2140, 3 9820, 2 8952]
B = [1 0 0 0.5, 2 0 0 0.8, 3 0 1 0, 4 0 1 0.5, 5 1 1 0, 6 1 1 0.5]
[tf,index1] = ismember(A,B(1:4:end));
index2 = 4*index1(tf) - [2 1 0]';
C = B(index2(:))
Kategorien
Mehr zu Logical finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!