Finding the first index in the datasets with a gap
5 views (last 30 days)
Show older comments
Hi there,
I have some data, which is attached, and I'd like to try to find the first index in the datasets. So I write some code, which I've attached, but I'm having trouble finding some indexes.
For example, there is a gap between finding the number 4 and finding the first index of 4 after this gap (figure). I also like to repeat the process for other numbers.
Any suggestions would be greatly appreciated.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1064120/image.jpeg)
0 Comments
Accepted Answer
Voss
on 13 Jul 2022
Let me reproduce your image first:
% load and plot data
data = readmatrix('Data.xls');
plot(data(:,1),data(:,2),'r','LineWidth',2)
hold on
% get the set of unique values in data(:,2), which is 1-7 in this case
vals = unique(data(~isnan(data(:,2)),2))
% find the first index of each value
Nvals = numel(vals);
first_idx = zeros(Nvals,1);
for ii = 1:Nvals
first_idx(ii) = find(data(:,2) == vals(ii),1);
end
% plot a blue marker at the first index of each value
plot(data(first_idx,1),data(first_idx,2),'ob','MarkerFaceColor','b')
Now, I'll include some code for finding the first index after a gap:
% initialize post-gap indices to NaN (not all values have a gap - use NaN to tell which)
post_gap_idx = NaN(Nvals,1);
for ii = 1:Nvals
% Find the first location after the first instance of vals(ii) in data(:,2)
% where data(:,2) is NOT equal to vals(ii). That is, after data(:,2) goes
% to vals(ii), non_val_idx is the first location where data(:,2) has some
% other value:
non_val_idx = find(data(first_idx(ii)+1:end,2) ~= vals(ii),1) + first_idx(ii);
if isempty(non_val_idx)
% empty non_val_idx means that once data(:,2) goes to vals(ii), it
% remains there, so no gap exists and there's nothing to do in that case
continue
end
% here, we know that data(:,2) goes to vals(ii) and later changes to some
% other value, so now find the location where data(:,2) changes back to vals(ii):
back_to_val_idx = find(data(non_val_idx+1:end,2) == vals(ii),1) + non_val_idx;
if isempty(back_to_val_idx)
% empty back_to_val_idx means that data(:,2) never returns to vals(ii)
% once it switches away, so in this case as well there's no gap
continue
end
% here, we know that data(:,2) changes back to vals(ii) after having switched
% away (i.e., a gap), so store the location at which this happens as
% post_gap_idx(ii):
post_gap_idx(ii) = back_to_val_idx;
end
post_gap_idx
% only use the non-NaN values for plotting
temp = post_gap_idx(~isnan(post_gap_idx))
% plot a green marker at the post-gap locations
plot(data(temp,1),data(temp,2),'gs','MarkerFaceColor','g')
More Answers (0)
See Also
Categories
Find more on Language Fundamentals in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!