Inserting a row in a matrix in a precise place

1 回表示 (過去 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')
  1 件のコメント
KSSV
KSSV 2020 年 7 月 29 日
+1 common sense..

サインインしてコメントする。


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 Center および File ExchangeCreating 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