Search code examples
matlabindexingfindcompareindices

How can I write this efficiently without using loop in Matlab?


dist=[1:100]; % distance

% conc. is concentration of size 1x100

conc=1  1   1   1   1   1   1   1   1   1   1   1   1   1   1   0.990000000000000   0.990000000000000   0.990000000000000   0.990000000000000   0.990000000000000   0.990000000000000   0.990000000000000   0.990000000000000   0.990000000000000   0.990000000000000   0.990000000000000   0.980000000000000   0.970000000000000   0.950000000000000   0.920000000000000   0.890000000000000   0.850000000000000   0.820000000000000   0.790000000000000   0.750000000000000   0.710000000000000   0.680000000000000   0.640000000000000   0.600000000000000   0.560000000000000   0.520000000000000   0.480000000000000   0.440000000000000   0.400000000000000   0.360000000000000   0.310000000000000   0.270000000000000   0.230000000000000   0.180000000000000   0.140000000000000   0.100000000000000   0.0700000000000000  0.0400000000000000  0.0200000000000000  0.0100000000000000  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

I want to find index corresponding to the concentration value of 0.16 (or the closest value possible) and 0.84 (or the closest value possible) in conc. I will use that index to find dist at those indexes. One thing to note is that conc value is decreasing from 1 to 0 in a non-linear relationship in a vector of size 100. I know we can use find(), but I am not sure how it can be used for what I want to do.

I want to be able to do this efficiently without using loop if possible. This is because I have many vectors for concentration and there are already many loops in my code. Thanks.


Solution

  • A simple solution is

    [x, i] = min(abs(conc - 0.16));
    

    after which i will hold the index. This compares every element of the conc vector, which is kind of wasteful because the data is ordered and you could do a binary search, but the binary search implemented at matlab level would likely be slower for a hundred-element vector.