I am trying to match 1st column of A
with 1st to 3rd columns of B
, and append corresponding 4th column of B
to A
.
For example,
A=
1 2
3 4
B=
1 2 4 5 4
1 2 3 5 3
1 1 1 1 2
3 4 5 6 5
I compare A(:,1)
and B(:, 1:3)
1
and 3
are in A(:,1)
1
is in the 1st, 2nd, 3rd rows of B(:, 1:3)
, so append B([1 2 3], 4:end)'
to A
's 1st row.
3
is in the 2nd and 4th rows of B(:,1:3)
, so append B([2 4], 4:end)'
to A
's 2nd row.
So that it becomes:
1 2 5 4 5 3 1 2
3 4 5 3 6 5 0 0
I could code this using only for
and if
.
clearvars AA A B mem mem2 mem3
A = [1 2 ; 3 4]
B = [1 2 4 5 4; 1 2 3 5 3; 1 1 1 1 2; 3 4 5 6 5]
for n=1:1:size(A,1)
mem = ismember(B(:,[1:3]), A(n,1));
mem2 = mem(:,1) + mem(:,2) + mem(:,3);
mem3 = find(mem2>0);
AA{n,:} = horzcat( A(n,:), reshape(B(mem3,[4,5])',1,[]) ); %'
end
maxLength = max(cellfun(@(x)numel(x),AA));
out = cell2mat(cellfun(@(x)cat(2,x,zeros(1,maxLength-length(x))),AA,'UniformOutput',false))
I am trying to make this code efficient, by not using for
and if
, but couldn't find an answer.
A
orB
? – DivakarAA
(last line inside loop) you should use4:end
instead of[4,5]
. ANd your code runs quite fast/efficient. Would recommend to keep it, if no faster solution is found... there is no reason to avoid loops just that many times there is a faster solution without loops. – The Minionismember
, which means JIT cannot accelerate this loop effectively. For larger problems, this will becomes a concern. – Rody Oldenhuisfor-loop
but theismember()
inside the loop. Still when I ran his code and the one from Nishant, his was minimal faster even for 10.000x100 entries. So not sure if that "problem" withismember()
really results in such runtime issues. BTW nice solution +1 – The Minion