How to add specific rows to a matrix?
9 views (last 30 days)
Show older comments
I have a matrix A with 3 columns and multiple rows,
A =
a_1 b_1 2
a_1 b_1 3
a_1 b_1 2
a_2 b_2 6
a_2 b_2 8
a_3 b_3 3
a_3 b_3 9
a_3 b_3 5
a_3 b_3 4
... ... ...
For each couple of parameters (a_i, b_i) in A that appears less four times, I woud like to create a matrix B that contains additional rows "a_i b_i 0" for this couple of parameters, such that
B =
a_1 b_1 2
a_1 b_1 3
a_1 b_1 2
a_1 b_1 0 %added rows
a_2 b_2 6
a_2 b_2 8
a_2 b_2 0 %added rows
a_2 b_2 0 %added rows
a_3 b_3 3
a_3 b_3 9
a_3 b_3 5
a_3 b_3 4
... ... ...
Note that the value a_i and b_i ae not unique, but each couple (a_i, b_i) would be different from (a_j, b_j).
Thanks in advance!
2 Comments
Image Analyst
on 19 Feb 2022
Can you give an actual matrix with values?
I'm thinking that using findgroups() to find groups in the left column would be a part of the solution. If the length of any group is less than 4 you'd have to insert row(s).
Accepted Answer
Voss
on 19 Feb 2022
A =[
3.8 6.4 2.0
3.8 6.4 5.0
3.8 6.4 9.0
3.8 6.5 4.0
3.8 6.5 3.0
3.9 6.4 1.0
3.9 6.4 8.0
3.9 6.4 7.0
3.9 6.4 4.0
];
needed_rows = 4;
[uA,~,jj] = unique(A(:,[1 2]),'rows','stable');
n_uA = size(uA,1);
B = [repelem(uA,needed_rows,1) zeros(needed_rows*n_uA,1)];
for ii = 1:n_uA
idx = jj == ii;
B(needed_rows*(ii-1)+(1:nnz(idx)),3) = A(idx,3);
end
disp(B);
More Answers (1)
Image Analyst
on 19 Feb 2022
Not sure why you didn't try findgroups() like I suggested. Or maybe you have by now. You might have gotten something like this:
A =[
3.8 6.4 2.0
3.8 6.4 5.0
3.8 6.4 9.0
3.8 6.5 4.0
3.8 6.5 3.0
3.9 6.4 1.0
3.9 6.4 8.0
3.9 6.4 7.0
3.9 6.4 4.0
];
g = findgroups(A(:, 1))
neededRows = 8;
for k = 1 : max(g)
theseRows = g == k;
numInThisGroup = sum(theseRows);
if numInThisGroup < neededRows
lastRow = find(theseRows, 1, 'last');
rowsToAdd = neededRows - numInThisGroup;
% Insert rows.
A = [A(1:lastRow,:); repmat(A(lastRow, :), [rowsToAdd, 1]); A(lastRow+1:end, :)];
% Need to update g now.
g = findgroups(A(:, 1));
end
end
A
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!