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

16 ビュー (過去 30 日間)
NAS
NAS 2019 年 7 月 12 日
編集済み: Jon 2019 年 7 月 12 日
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
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
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);

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by