how to find where a value falls in a list
10 次查看(过去 30 天)
显示 更早的评论
I have a 2 x 1000 array (“A”) as shown in the first 2 columns. (I only include the first 10 rows). The values are in order.
Then I have another array(“B”) as shown in the third column, which is also in order. I want to find a set of weights that identify the weights of corresponding values in the first two columns.
For example, .029 is in between .000 and .053 with respective weights 0.72 and 0.28. Also, .117 is between .105 and .157
How do i calculate the 4 columns of “C” shown below. If I know C(1.x), i can do the rest, but need to identify the Index immediately before each of the values in B.
chart appears below
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1559259/image.png)
4 个评论
Taylor
2023-12-4
idx = find(A(:,2) < B(1), 1)
In this case, the find function will return the index where the first value of the second column of A that is smaller than the first value of B occurs.
采纳的回答
Voss
2023-12-4
A = [
1 0
2 0.053
3 0.105
4 0.157
5 0.208
6 0.258
7 0.306
8 0.353
9 0.399
10 0.442
];
B = [
0.015
0.029
0.044
0.059
0.073
0.088
0.102
0.117
0.132
];
One way to determine the index in A(:,2) of the first element greater than each element of B:
N = numel(B);
idx = zeros(N,1);
for ii = 1:N
idx(ii) = find(A(:,2) > B(ii), 1);
end
Another way to do the same:
[~,idx] = max(A(:,2) > B(:).', [], 1);
Then the matrix C is:
C = [idx(:)-[1 0] [A(idx,2)-B B-A(idx-1,2)]./(A(idx,2)-A(idx-1,2))]
Of course, if all you want to do with all this is to interpolate something, then you can let interp1 do the calculations of the weights and whatnot for you.
2 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!