Matching two array elements by rounding up and down

2 次查看(过去 30 天)
Dear mathworks community,
I need to create a conditional array that I find quite challenging. I uploaded an example data list and result that shows what I need to have at the end as both Excel file and txt file.
I have a reference list that is a column vector. It contains numbers from -10 to 10 with step size of 1 as in the uploaded file and I have a secondary list that contains numbers from -10 to 10 again, but the step sizes differ and list B can be shorter than list A. What I need to do is this:
I need to match the elements of two lists by rounding up or down the elements of list B and the below condition should apply:
if |listA(n) – listB(m)| < |listA(n) – listB(m+1)|
listA(n) matches with listB(m).
So each member of listA matches with the closest element of listB.
Also, if there is no closer value of listB(m) to listA(n), then, listB(m) can be used multiple times.
For example,
listA(n) = -5, listA(n+1) = -6 ,
listB(m) = -4.6, listB(m+1) = -5.2, listB(m+2) = -5.8 and listB(m+3) = -6.5
listA(n) - listB(m) = |-5-(-4.6)| = 0.4
listA(n) - listB(m+1) = |-5 – (-5.2)| = 0.2
since 0.2 < 0.4 listA(n) matches with listB(m+1)
and listA(n+1) - listB(m+2) = |-6 – (-5.8)| = 0.2,
listA(n+1) - listB(m+3) = |-6-(-6.5)| = 0.5
so listA(n+1) matches with listB(m+2)
Note: The difference between the elements of list A and list B can be greater than 1, still the same rule applies.
Note2: This is not a homework. I just need to calculate rms of the difference between reference list and secondary list.

采纳的回答

dpb
dpb 2023-4-18
移动:dpb 2023-4-18
fn='https://www.mathworks.com/matlabcentral/answers/uploaded_files/1359918/data_list.txt';
tT=readtable(fn);
ix=isfinite(tT.B);
tT.C=interp1(tT.B(ix),tT.B(ix),tT.A,'nearest','extrap')
tT = 21×3 table
A B C ___ _____ _____ -10 -9.4 -9.4 -9 -7.85 -9.4 -8 -5.6 -7.85 -7 -4.1 -7.85 -6 -2.6 -5.6 -5 -1.1 -5.6 -4 0.4 -4.1 -3 1.9 -2.6 -2 3.4 -2.6 -1 4.9 -1.1 0 6.4 0.4 1 7.9 0.4 2 9.4 1.9 3 NaN 3.4 4 NaN 3.4 5 NaN 4.9

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by