MATLAB Answers


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

Asked by Nicole Schwery on 12 Jul 2019
Latest activity Edited by Jon
on 12 Jul 2019
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.
plot(x,y,'r');hold on; plot(x,y2);
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');
here is what I am getting on the command window:
values =
290.0000 953.2529
values =
746.0000 997.1494


Sign in to comment.


2 Answers

Answer by Cristian Garcia Milan on 12 Jul 2019
 Accepted Answer

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:
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;

  1 Comment

Thank you so much!! I appreciate it.

Sign in to comment.

Answer by Jon
on 12 Jul 2019
Edited by Jon
on 12 Jul 2019

You can also do all of that without any loops as follows
% load the data
load data
% 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
% add a horizontal line at the threshold value


Sign in to comment.