## Need to store each index and value from if statement inside the for loop.

### Nicole Schwery (view profile)

on 12 Jul 2019
Latest activity Edited by Jon

### Jon (view profile)

on 12 Jul 2019
Accepted Answer by Cristian Garcia Milan

### Cristian Garcia Milan (view profile)

My code is finding the points that are crossing the horizontal line. My code stores the last index and value but it doesn't store each one from the loop. I want to be able to see each iteration with its index and value. Thank you.
I've attached the data.
x=1:length(data);
y=data;
y2=970.7573*(ones(length(x)));
plot(x,y,'r');hold on; plot(x,y2);
values=[];
for i=1: length(x)-1
if ( y(i)>y2 & y(i+1) < y2) | ( y(i)<y2 & y(i+1) > y2)
values=[i y(i)]
plot(i , y(i) , 'o');
end
end
----
here is what I am getting on the command window:
values =
290.0000 953.2529
values =
746.0000 997.1494

### Cristian Garcia Milan (view profile)

on 12 Jul 2019

Hi Nicole,
I can see that in your loop you are assigning the values variable each time the statement is true. If you want to store these data you have to add them to a new row each time the statement comes true.
Try with the following:
values=zeros(1,2);
p=1;
for i=1: length(x)-1
if ( y(i)>y2 & y(i+1) < y2) | ( y(i)<y2 & y(i+1) > y2)
values(p,:)=[i y(i)];
plot(i , y(i) , 'o');
p = p+1;
end
end

Nicole Schwery

### Nicole Schwery (view profile)

on 12 Jul 2019
Thank you so much!! I appreciate it.

on 12 Jul 2019
Edited by Jon

### Jon (view profile)

on 12 Jul 2019

You can also do all of that without any loops as follows
% assign the y vector to the data
y = data;
% assign a value to the horizontal line (threshold) that you are checking
% for crossings
threshold = 970.7573
% make an x vector to go along with the data
x = 1:length(y);
% make a vector that has a value of 1 for all of the values greater than
% the threshold and -1 for all of the values below the threshold
ySwitch = sign(y - threshold);
% find the indices where the sign changes
iSwitch = find(diff(ySwitch)~=0);
% plot the data, and the switch points
% note that in this case x(iSwitch) = iSwitch, but this is a little more
% general, in case your x vector wasn't just the index
plot(x,y,'r',x(iSwitch),y(iSwitch),'o')
% add a horizontal line at the threshold value
yline(threshold);