find all similar index of array in Matlab

前端 未结 3 1528
轮回少年
轮回少年 2021-01-26 06:06

I have a array X=[1 2 3 1.01 2.01 4 5 1.01 3.01] I want to all index of this array are similar and difference<=0.01 in matlab answer is



        
3条回答
  •  悲哀的现实
    2021-01-26 06:37

    I think the submission "unique with tolerance" in the FileExchange is for you.

    You should note, that creating the variables X1...X5 as separate variables is a bad idea and a bad practice, because this makes referencing these values in later code (which is either vectorized or loop-based) cumbersome and inefficient. More correct alternatives to storing the data are cells (like in the solution suggested by Daniel) or in structs.

    Having said that, if for some reason you still want to create uniquely named variables, this is possible using a mix of the aforementioned submission (uniquetol) and eval:

    [~,b,c]=uniquetol(X,0.01+eps);
    for ind1 = 1:length(b)
        eval(sprintf('X%d = (find(c==X(b(%d))))'';',ind1,ind1)); 
    end
    

提交回复
热议问题