Inserting a row in a matrix in a precise place
3 次查看(过去 30 天)
显示 更早的评论
Hi, I need a support with this problem.
I have a matrix in which values of the first column are in ascending order. For example: A = [ 2 8 3 11 ; 13 33 4 5 ; 18 8 4 7 ; 23 4 6 11 ] ;
Now, I have a row vector and I need to insert it in A in order to maintain the ascending order of the first column. Let's say I have b = [ 8 4 23 9 ], I want to overwrite A, obtaining:
A = [ 2 8 3 11 ; 8 4 23 9 ; 13 33 4 5 ; 18 8 4 7 ; 23 4 6 11 ] ;
At first I tried with:
row = max(find(A(:,1)<b(1)+1));
A = [ A(1:row,:) ; b ; A(row+1:end,:)] ;
It worked, until I realized that b(1) can't be less than A(1,1). In fact if b had been [ 1 4 23 9 ], "row" would have been empty and I would not be able to insert the vector at the head of A.
I'm trying to avoid too many ifs and I can't use sortrows because afterwards I have to insert a logical vector to a logical matrix in the same place where I added b to A. I have to know where b is added since sortrows would not work in that case.
Thanks to anyone who can help me!
2 个评论
Bruno Luong
2020-7-29
编辑:Bruno Luong
2020-7-29
Read from the question: "I can't use sortrows because afterwards I have to insert a logical vector to a logical matrix in the same place where I added b to A."
Actually this is not right, you are able to know exactly where b is inserted by using the second argument of SORTROWS
[A,i] = sortrows([b;A],1)
locb = find(i==1)
or
[A,i] = sortrows([A;b],1)
locb = find(i==size(A,1))
The difference between the two methods is that in case of draw between b(1) and A(r,1) for some r, b is inserted above the row #r (first case) or below row #r (second case).
This seems to be a big hammer to accomplish the task though.
回答(3 个)
madhan ravi
2020-7-29
编辑:madhan ravi
2020-7-29
z = sortrows([A; b], 1);
[b_logical, b_where] = ismember(b, z, 'rows')
Bruno Luong
2020-7-29
编辑:Bruno Luong
2020-7-29
[~,r] = histc(b, [A(:,1); Inf]);
Ab = [A(1:r,:); b; A(r+1:end,:)]; % r+1 is the row-position of b in the new array
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!