Need to store each index and value from if statement inside the for loop.
16 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Cristian Garcia Milan
2019-7-12
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
更多回答(1 个)
Jon
2019-7-12
编辑:Jon
2019-7-12
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!