how to find indices that fulfil a certain criteria
Afficher commentaires plus anciens
Lets say I want to write a script and the input is the following vector:
vector = [1 1 1 1 3 3 3 9 9 9 9 2 2 1 1 1 2 7 9 7 2 1 1 1]
I want the result to be a new vector that contain the indices [12 21] (the two 2's in bold and italic). The script should chose these indices because they are the first to follow index 7 and 17 (in bold) and at the same time have a value of that particular index +/- one... I hope it make sense and that it is doable. Thanks Michael
Réponse acceptée
Plus de réponses (1)
vector = [1 1 1 1 3 3 3 9 9 9 9 2 2 1 1 1 2 7 9 7 2 1 1 1];
refindices = [7 17];
outindices = zeros(size(refindices));
for refi = 1:numel(refindices)
refindex = refindices(refi);
outindex = find(abs(vector(refindex+1:end) - vector(refindex)) <= 1, 1);
if ~isempty(outindex)
outindices(refi) = refindex + outindex;
else
%whatever you want to do or nothing if you want 0 when criteria is not found
end
end
would be one way to do it.
Another option, sort of avoiding the loop (the loop is implemented by cellfun):
vector = [1 1 1 1 3 3 3 9 9 9 9 2 2 1 1 1 2 7 9 7 2 1 1 1];
refindices = [7 17];
splitvector = mat2cell(vector, 1, diff([1 refindices numel(vector)+1]));
outindices = refindices + cellfun(@(subv) find(abs(subv(2:end) - subv(1)) <= 1, 1), splitvector(2:end));
1 commentaire
Michael Clausen
le 17 Sep 2014
Catégories
En savoir plus sur Time Series Objects dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!