indexing multiple values in two arrays with different size

5 ビュー (過去 30 日間)
Pietro
Pietro 2019 年 2 月 13 日
コメント済み: madhan ravi 2019 年 2 月 15 日
I have a simple problem that unfortunately I am failiing so solve (and to find solutions in internet).
Assuming I have 2 matrixes
a = [1 1 1 1 2 2 2 2 2 5 5 5; 0 0 0 0 0 0 0 0 0 0 0 0]';
b = [1 2 5; 11 12 15]';
I would like (without a for loop, that is my current, very slow implementation) to assign in a the corresponding values in the second column of b, when a(x, 1) == b(x,1). Basically the final result should be
a = [1 1 1 1 2 2 2 2 2 5 5 5; 11 11 11 11 12 12 12 12 12 15 15 15]
Thanks a lot for any help

採用された回答

madhan ravi
madhan ravi 2019 年 2 月 13 日
A=sum(a(:,1)==b(:,1).');
a(:,2)=repelem(b(:,2),A).'
  1 件のコメント
madhan ravi
madhan ravi 2019 年 2 月 13 日
For version prior to 2016b:
A=sum(bsxfun(@eq,a(:,1),b(:,1).'));
a(:,2)=repelem(b(:,2),A).'

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

その他の回答 (1 件)

Pietro
Pietro 2019 年 2 月 14 日
I received also another way to do it
a(:,2) = interp1(b(:,1), b(:,2), a(:,1));
I do not know which one is the more efficient, but both solutions work
I will use this one as it is only 1 line of code instead of two
Thanks for the support
  4 件のコメント
Pietro
Pietro 2019 年 2 月 15 日
Unfortunately your method does not work because this operation
A=sum(a(:,1)==b(:,1).');
requires too much memory (in my case b(:,1) is bigger than 1M values), so even if more efficient in speed, it is not very efficient in memory management (the tipical trade off)
Thanks anyway
madhan ravi
madhan ravi 2019 年 2 月 15 日
So instead of creating variable A in workspace why not directly implement it ?
a(:,2)=repelem(b(:,2),sum(a(:,1)==b(:,1).')).';

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by