adding rows to array with order

2 ビュー (過去 30 日間)
sermet
sermet 2016 年 5 月 19 日
回答済み: Guillaume 2016 年 5 月 20 日
data=[1.0452;1.0645;1.1027;1];
fixed_data=[1;1.0452];
for i=1:numel(fixed_data)
idx(i)=find(fixed_data(i)==data);
end
other_data=[1.064562;1.102656];
I need to merge fixed_data and other_data w.r.t idx as follows;
merged_data=[1.0452;1.064562;1.102656;1];
idx (4 1) determines 4th row of merged_data equals fixed_data(1) and first row of merged data equals fixed_data(2). Matrix dimensions are variable so I need to perform this as an automatic way for any situation.
  1 件のコメント
sermet
sermet 2016 年 5 月 19 日
idx determines the order of merged_data w.r.t. fixed_data. idx (4 1) determines 4th row of merged_data equals fixed_data(1) and first row of merged data equals fixed_data(2).

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

採用された回答

Guillaume
Guillaume 2016 年 5 月 20 日
Note: this only works if all the elements of fixed_data are unique and only found once in data and if numel(fixed_data) + numel(other_data) == numel(data):
assert(numel(fixed_data) == numel(unique(fixed_data)), 'Duplicated values in fixed_data');
assert(numel(fixed_data) + numel(other_data) == numel(data), 'Vector sizes do not match');
[infixed, location] = ismember(data, fixed_data);
assert(numel(nonzeros(location)) == numel(unique(nonzeros(location))), 'Fixed_data found multiple times in data');
merged_data = data;
merged_data(~infixed) = other_data
You can take the asserts out if you're sure that the preconditions are fulfilled.

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 5 月 19 日
編集済み: Azzi Abdelmalek 2016 年 5 月 19 日
data=[1.0452;1.0645;1.1027;1]
fixed_data=[1;1.0452]
other_data=[1.064562;1.102656]
%---------------------------------
merged_data=data
idx=ismember(data,fixed_data)
merged_data(idx)=fixed_data
merged_data(~idx)=other_data
  3 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2016 年 5 月 19 日
Use
format long
merged_data
you will see the difference
sermet
sermet 2016 年 5 月 20 日
編集済み: sermet 2016 年 5 月 20 日
Azzi, true merged_data is
merged_data=[1.0452;1.064562;1.102656;1];
your code produces
merged_data=[1;1.064562;1.102656;1.0452]

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

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by