# Plot segments of an array with NaN using a for loop

1 view (last 30 days)
Jose Rego Terol on 2 Mar 2021
Commented: Jose Rego Terol on 7 Mar 2021
Hi,
I got an array with NaN. I want to plot, step-by-step, those segments of integers, that exceed a threshold and flanked by NaN, using a for loop.
Example:
Threshold=5
A=[NaN 1 2 3 4 4 3 1 NaN 2 4 5 10 11 12 14 13 11 7 5 3 NaN 2 3 7 15 20 25 17 13 9 5 1 NaN]
So, I want the loop to take the second segment of the integers flanked by NaN (2 - 3) and plot them. Then, I will do some operations with the plot, and I will continue with the loop using a wait(X) for the third segmentt (2 - 1).
The array always starts with a NaN, and finishes with an NaN.
for i = 1:length(A)
% code for getting the plot and make the operation
wait(next_plot)
end
At least, if I can plot the second and the third segment together skipping the first one, I would save my day.
Best,
Jose

dpb on 2 Mar 2021
Edited: dpb on 2 Mar 2021
Rough outline to accomplish --
ix=find(isnan(A)); ix=ix(2:end); % find the NaN sections, ignore first
for i=1:numel(ix)-1 % over the groups
subplot(2,1,i); % just to show the separate pieces;
x=ix(i):ix(i+1); % set the x values to match
B=A(x); % select the portion wanted from A this group
B(B<=Threshold)=nan; % don't plot those <= Threshold
plot(x,B,'*-') % plot verus original ordinal position
end
If only want the values above the threshold, then delete those below (or select only those above) instead and the corresponding x values to match.
##### 2 CommentsShowHide 1 older comment
Jose Rego Terol on 7 Mar 2021
Well, I got a workaround with numel()
for i=1:numel(ix)-1 % numel(ix)-1 over the groups
f=numel(find(Trial((ix(i):ix(i+1)),2)>15));
if f == 0
disp('no spike')
else
plot(Trial((ix(i):ix(i+1)),1),Trial((ix(i):ix(i+1)),2))
end
pause()
% plot(i); % just to show the separate pieces;
% pause()
% x=ix(i):ix(i+1); % set the x values to match
% B=Trial(x,2); % select the portion wanted from A this group
% B(B<=Threshold)=nan; % don't plot those <= Threshold
% plot(x,B) % plot verus original ordinal position
end
Now, if the segment does not have any value higher than 15, matlab disp 'no spike'.
Thanks for the first line. It push the code to do what I want to do.