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
Y=cell(5,1)
for idx=1:numel(Y)
Y{idx}=find(abs(X-idx)<=.2);
end
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
Here a solution using for-loop. Not sure about efficiency though. Gonna try to find another solution as well.
X=[1 2 3 1.01 2.01 4 5 1.01 3.01]
result=cell(length(X),1);
boarder = 0.01;
for n=1:length(X)
helper = X(n);
Y=X;
Y(X>helper+boarder)=0;
Y(X<helper-boarder)=0;
result(n,1)={find(Y)};
end
I predefine a cellarray (result
) which contains all index (for each element of X). Then I loop over the elements setting those who are outside of your boarder to 0. Last but not least I save the index to the result array.
Obviously some results are the same but this way you get also results for the case: X=[ 1.01, 1.02, 1.03, 1.04,...];
And if you want to delete those elements which are the same you could loop over your data again and get unique
results.