Embedding an array into another: vectorization method

I have two arrays. The first one is a consecutive sequential one, like:
seq1 =
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
...continues
The second one is like:
seq2 =
2 250
3 260
5 267
6 270
8 280
10 290
13 300
18 310
20 320
21 330
...continues
I need to embed `seq2` into `seq1` in such a way that I end up with the sequence:
seq3 =
1 0
2 250
3 260
4 260
5 267
6 270
7 270
8 280
9 280
10 290
11 290
... continues
I could do this with loops but the arrays are really big so I don't want to use two `for` loops, it is taking too long. How can I do this in a vectorised manner?

2 件のコメント

dpb
dpb 2017 年 5 月 25 日
What are p, q, r, ... ? Constants, additional vectors, ... ?
Tanmay
Tanmay 2017 年 5 月 25 日
編集済み: Tanmay 2017 年 5 月 25 日
Constant numbers. I've edited the question so its clearer.

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

 採用された回答

Andrei Bobrov
Andrei Bobrov 2017 年 5 月 25 日
編集済み: Andrei Bobrov 2017 年 5 月 25 日

1 投票

seq1 = (1:10);
seq2 = {2,'p';5,'q';7,'r';10,'s';33,'t'};
n = [seq2{:,1}]';
s = seq1(:);
i0 = (min(min(s),min(n)):max(max(s),max(n)))';
[l0,ii] = ismember(i0,n);
idx = cumsum(l0);
t = idx ~= 0;
out = num2cell(i0);
out(t,2) = seq2(idx(t),2);
out(~t,2) = {0};
ADD
A = [
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0 ];
B = [
2 250
3 260
5 267
6 270
8 280
10 290
13 300
18 310
20 320
21 330 ];
Z = (min([A(:,1);B(:,1)]):max([A(:,1);B(:,1)]))';
l0 = ismember(Z,B(:,1));
ii = cumsum(l0);
t = ii ~= 0;
Z(t,2) = B(ii(t),2);

1 件のコメント

Tanmay
Tanmay 2017 年 5 月 25 日
Very elegant, thank you so much!

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

その他の回答 (1 件)

Stephen23
Stephen23 2017 年 5 月 25 日
編集済み: Stephen23 2017 年 5 月 25 日

2 投票

One very simple and efficient way is to use interp1 with its previous option:
>> A = [
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0 ];
>> B = [
2 250
3 260
5 267
6 270
8 280
10 290
13 300
18 310
20 320
21 330 ];
>> Z = A;
>> Z(:,2) = interp1(B(:,1),B(:,2),A(:,1),'previous')
>> Z =
1 NA
2 250
3 260
4 260
5 267
6 270
7 270
8 280
9 280
10 290

2 件のコメント

Andrei Bobrov
Andrei Bobrov 2017 年 5 月 25 日
編集済み: Andrei Bobrov 2017 年 5 月 25 日
+1
Z = (min([A(:,1);B(:,1)]):max([A(:,1);B(:,1)]))';
Z(:,2) = interp1(B(:,1),B(:,2),Z,'previous');
Tanmay
Tanmay 2017 年 5 月 25 日
Wasn't aware of this function, thank you!

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

カテゴリ

質問済み:

2017 年 5 月 25 日

コメント済み:

2017 年 5 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by