MATLAB Answers

Inserting a row in a matrix in a precise place

8 views (last 30 days)
Francesco Cattaneo
Francesco Cattaneo on 29 Jul 2020
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 Comments

Bruno Luong
Bruno Luong on 29 Jul 2020
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.
Francesco Cattaneo
Francesco Cattaneo on 29 Jul 2020
Thankyou, didn't read about the second argument of sortrows. There's no possibilities of draw values in the code.

Sign in to comment.

Answers (3)

madhan ravi
madhan ravi on 29 Jul 2020
Edited: madhan ravi on 29 Jul 2020
z = sortrows([A; b], 1);
[b_logical, b_where] = ismember(b, z, 'rows')

KSSV
KSSV on 29 Jul 2020
Edited: KSSV on 29 Jul 2020
A = [ 2 8 3 11 ; 13 33 4 5 ; 18 8 4 7 ; 23 4 6 11 ] ;
b = [ 8 4 23 9 ] ;
idx = find(A(:,1)<b(1))+1 ; % get the positon where to insert
iwant = [A(1:idx-1,:) ;b ; A(idx:end,:)]

  0 Comments

Sign in to comment.


Bruno Luong
Bruno Luong on 29 Jul 2020
Edited: Bruno Luong on 29 Jul 2020
[~,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 Comments

Sign in to comment.

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!