problems using for loop
조회 수: 8 (최근 30일)
이전 댓글 표시
%PULSE GENERATION
for k=1:length(t)
if mod(t(1,k),ts) == 0
pulse1(1,k) = 1
else
pulse1(1,k) = 0
end
end
here is a code snippet written by me for generating a pulse i have taken ts = 0.02 and t = 1:0.0001:2 for a project but when ever I run this programme it just keeps on looping. But sometimes its stops and shows a blizzare graph which is not at all looks like a pulses. I use Matlab R2018a
%PULSE GENERATION
for k=1:length(t)
if mod(t(1,k),Ts)==0
pulse(1,k)=1 %PULSE
else
pulse(1,k)=0;
end
end
while this above code written by my friend is completely fine and runs smoothly.
What is the difference between these two code snippets apart from the intendation? What problem lies in the intendation of the programme?
댓글 수: 0
답변 (1개)
Bruno Luong
2020년 8월 28일
편집: Bruno Luong
2020년 8월 28일
Both codes are flawed, this statement is flawed (neverr compare floating points with "==")
if mod(t(1,k),Ts) == 0
You should replace with something like
dt =0.0001; % your time step dt=mean(diff(t))
for ...
tk = t(1,k);
tdiff = tk-ceil(tk/Ts)*Ts;
if tdiff+dt > 0
...
else
...
end
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!