配列の長さが違う2つの配列を揃える方法
84 views (last 30 days)
Show older comments
配列の長さが違う2つの配列を、同じ長さに合わせるためには、どのような方法があるでしょうか?
(例)
A = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] ;
B = [10,NaN,NaN,NaN,1,NaN,5,NaN,NaN,-1];
配列Bのデータは不等間隔でサイズも配列Aと異なります。
この配列Bを20等分し長さを揃えた
C = [10,9,8,7,6,5,4,3,2,1,2,3,4,5,4,3,2,1,0,-1] ;
が必要です。
*実際の配列は数万行あります。
この配列Cは線形で補完できるものです。
よろしくお願いします。
0 Comments
Accepted Answer
michio
on 4 Mar 2020
その条件ですとパッと思いつくのは linspace 関数でした。2つの値の間を線形補間します。
B = [10 1];
C = linspace(B(1),B(2),length(A))
C =
10 9 8 7 6 5 4 3 2 1
linspace 関数の詳細はこちら
4 Comments
michio
on 5 Mar 2020
例えば
B = [10,NaN,NaN,NaN,1,NaN,5,NaN,NaN,-1]; % もとの配列
idx = ~isnan(B);
position = find(idx); % NaN ではない要素位置を取得
% 1 から length(B) までを均等に20分割した点において、内挿値を計算。
C = interp1(position, B(idx), linspace(1,length(B),20))
と実行すると
C =
1 列から 15 列
10.0000 8.9342 7.8684 6.8026 5.7368 4.6711 3.6053 2.5395 1.4737 1.5263 2.4737 3.4211 4.3684 4.6842 3.7368
16 列から 20 列
2.7895 1.8421 0.8947 -0.0526 -1.0000
が得られます。参考になりましたら。
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!