Azzera filtri
Azzera filtri

Finding the first index in the datasets with a gap

3 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Voss
Voss il 13 Lug 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))
vals = 7×1
1 2 3 4 5 6 7
% 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
post_gap_idx = 7×1
43091 34961 NaN 22678 NaN NaN NaN
% only use the non-NaN values for plotting
temp = post_gap_idx(~isnan(post_gap_idx))
temp = 3×1
43091 34961 22678
% plot a green marker at the post-gap locations
plot(data(temp,1),data(temp,2),'gs','MarkerFaceColor','g')

Più risposte (0)

Categorie

Scopri di più su Language Fundamentals in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by