Triangle_wave question
    조회 수: 5 (최근 30일)
  
       이전 댓글 표시
    

In this question, I have used the debugging tool in matlab and checked step by step. Everything looks fine. However, when I test my codes in the whole, everything seems broken. Could someone give me a hint how to fix my codes? Previously, someone has posted his codes for the same question, but my codes do not have the same issues. In particular, when n=10, the first element of v should be 0, but i got something different. The weird thing is that i did get 0 when debugging.
if true
  % function v = triangle_wave(n)
me=zeros(1,n+1);
v=zeros(1,1001);
for t = 0:4*pi
  for i=1:1001
      for k = 0:n
       me(k+1) = ((-1).^k)*sin(2.*k.*t+t)./(2.*k+1).^2;
      end
  v(i)=sum(me);
   k = k+1;
t=t+4*pi/1000;
i=i+1;
  end
end
end
댓글 수: 0
답변 (1개)
  Star Strider
      
      
 2018년 6월 29일
        You have coded the essential loop correctly. The problem is that you overloaded your code with a lot of irrelevant items. I would increase the resolution of ‘t’, and simply use the ‘k’ loop:
t = linspace(0,4*pi);
n = 100;
me = zeros(n+1, numel(t));
for k = 0:n
    me(k+1,:) = ((-1).^k)*sin(2.*k.*t+t)./(2.*k+1).^2;
end
me = sum(me);
figure
plot(t, me)
The plot is not necessary for the code. It simply shows the result.
Experiment to get the result you want.
댓글 수: 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!

