So you have a matrix A
:
A = [a 2 5 8;
b 4 8 NaN];
I'll first split the matrix into parts consisting of a
and b
and the rest:
a_and_b = A(:,1:3);
Arest = A(:,4:end);
then we'll see what the unique items are in this Arest
matrix, and remove the NaN
s:
Arest_uniq = unique(Arest);
Arest_uniq = Arest_uniq(~isnan(Arest_uniq));
check the occurences of the elements in Arest_uniq
in rows of Arest
:
occur_A = arrayfun(@(ii) ismember(Arest_uniq,Arest(ii,:)),1:size(A,1),'uni',false);
Because adding those rows a
and/or b
based on an if-construction isn't a linear operation, I'd rather just do it in a loop.
output = num2cell(Arest_uniq);
for ii=1:numel(output)
for jj=1:size(A,1)
if occur_A{jj}(ii)
output{ii} = [output{ii} a_and_b(jj,:)];
end
end
end
Go through this with step-by-step debugging, inspect variables on the way, and eventually you'll understand what everything does. So next time you can solve your problems yourself on the spot.