How to add specific rows to a matrix?
9 次查看(过去 30 天)
显示 更早的评论
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 个评论
Image Analyst
2022-2-19
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).
采纳的回答
Voss
2022-2-19
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);
更多回答(1 个)
Image Analyst
2022-2-19
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!