Inserting a row in a matrix in a precise place

조회 수: 3 (최근 30일)
Francesco Cattaneo
Francesco Cattaneo 2020년 7월 29일
댓글: Francesco Cattaneo 2020년 7월 29일
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
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.
Francesco Cattaneo
Francesco Cattaneo 2020년 7월 29일
Thankyou, didn't read about the second argument of sortrows. There's no possibilities of draw values in the code.

댓글을 달려면 로그인하십시오.

답변 (3개)

madhan ravi
madhan ravi 2020년 7월 29일
편집: madhan ravi 2020년 7월 29일
z = sortrows([A; b], 1);
[b_logical, b_where] = ismember(b, z, 'rows')

KSSV
KSSV 2020년 7월 29일
편집: KSSV 2020년 7월 29일
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,:)]

Bruno Luong
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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by