Need to store each index and value from if statement inside the for loop.
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
NAS
el 12 de Jul. de 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.
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
0 comentarios
Respuesta aceptada
Cristian Garcia Milan
el 12 de Jul. de 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
Más respuestas (1)
Jon
el 12 de Jul. de 2019
Editada: Jon
el 12 de Jul. de 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
plot(x,y,'r',x(iSwitch),y(iSwitch),'o')
% add a horizontal line at the threshold value
yline(threshold);
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!