I want to find particular values of t at which y becomes 2 (by writing some commands in code itself). Can I extract such values of t as a vector?

조회 수: 2 (최근 30일)
clear
clc;
N=2000; % Number of time stpes
dt=0.05; %Time step
%Initialize
y=zeros(N,1);
t=zeros(N,1);
%Initial values
t(1)=0;
y(1)=1;
for j=2:N
t(j)=t(j-1)+dt;
y(j)=y(j-1)+dt*sin(t(j-1));
end
plot(t,y)

채택된 답변

Star Strider
Star Strider 2018년 4월 23일
Try this:
N=2000; % Number of time stpes
dt=0.05; %Time step
%Initialize
y=zeros(N,1);
t=zeros(N,1);
%Initial values
t(1)=0;
y(1)=1;
for j=2:N
t(j)=t(j-1)+dt;
y(j)=y(j-1)+dt*sin(t(j-1));
end
zci = @(v) find(v(:).*circshift(v(:), [-1 0]) <= 0); % Returns Approximate Zero-Crossing Indices Of Argument Vector
idx_2 = zci(y - 2); % Vector Of Approximate Indices Where ‘y=2’
for k = 1:numel(idx_2)
t2(k) = interp1(y(idx_2(k)+[-1 1]), t(idx_2(k)+[-1 1]), 2, 'linear','extrap'); % Interopolate: ‘t’ Where ‘y=2’
end
figure
plot(t,y)
hold on
plot(t2, 2*ones(size(t2)), 'pg')
hold off
This uses the ‘zci’ utility function to find the approximate indices where ‘t=2’, then uses the ‘idx_2’ index vector to loop through your data to find the closest values of ‘t’ that the interp1 function can calculate where ‘y=2’.
  댓글 수: 16
Dharma
Dharma 2018년 5월 30일
Thanks. Actually I was using the same as you suggested (Except in comment where I wrote r=0.4). I found solution as well. If I choose value of r smaller than 0.2 then I will be able to increase N. Do you have any suggestion for this?
zci = @(v) find(v(:).*circshift(v(:), [-1 0]) <= 0);
idx_2 = zci(r - 0.2);
for m = 1:numel(idx_2)
t2(m) = interp1(r(idx_2(m)+[-1 1]), t(idx_2(m)+[-1 1]), 0.2, 'linear','extrap');
% Interpolate t where r=0.4
end
Also in the line interp1(r(idx_2(m))+[-1 1], what does [-1 1] represent?
Thank you again!
Star Strider
Star Strider 2018년 5월 30일
My pleasure.
‘If I choose value of r smaller than 0.2 then I will be able to increase N. Do you have any suggestion for this?’
I have no idea what you are doing, so I cannot answer that.
‘Also in the line interp1(r(idx_2(m))+[-1 1], what does [-1 1] represent?’
That vector creates a region ±1 indices around the chosen point, creating a region over which interp1 can interpolate. It is designed to create a strictly monotonic region in a function that may not otherwise be monotonic.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Benjamin Großmann
Benjamin Großmann 2018년 4월 23일
You could rewrite your function so that your wanted data points are maxima and search them with findpeaks.
[~,locs] = findpeaks(-abs(y-2));
plot(t,y,t(locs),y(locs),'or')
The pretty simple and elegant t2 = t(y==2) does not work here, since your data is not exaxtly two at any given entry.

카테고리

Help CenterFile Exchange에서 Bartlett에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by