Help with For-Loop question?
조회 수: 1 (최근 30일)
이전 댓글 표시
I keep getting the same error, about not being any real or logical answer.
here is the question; Create a time vector x = 0:2*pi. Using a for-loop, plot ten different curves on the same graph where the first curve is x1 = sin(x), the second curve is x2 = sin(x1), the third curve is x3 = sin(x2) and so on. Note that by using a for-loop it is not necessary to create ten separate variables to solve this problem.
Here is what I've been entering
x=0
>> for i=[pi/5:pi/5:2*pi]
x(i)=sin(x(i-(pi/5)))
end
??? Attempted to access x(0); index must be a positive integer or logical.
Any help would be appreciated
댓글 수: 0
채택된 답변
Robert
2011년 10월 5일
N=10;
x=zeros(N,numel(pi/5:pi/5:2*pi));
x(1,:)=pi/5:pi/5:2*pi;
for j=2:N
x(j,:)=sin(x(j-1,:));
end
plot(x(1,:),x')
댓글 수: 0
추가 답변 (1개)
Walter Roberson
2011년 10월 5일
t = 0:pi/5:2*pi;
curvenums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for K = 1 : numel(curvenums)./size(curvenums,1)
if ~curvenum(K)
x(:,curvenum(K+1)) = sin(t);
else
x(:,curvenum(K+1)) = sin(x(:,curvenum(K)));
end
end
plot(t,x)
댓글 수: 2
Robert
2011년 10월 5일
That seems needlessly complicated. Why do you keep track of a "curvenum" array that is just 0:9? See my reply below.
Walter Roberson
2011년 10월 5일
The posting is clearly a homework assignment. The code I provided is functional but would get no marks from any marginally alert marker as it would obviously not be written by the student. It is code that can be learned from but not profitably cloned as the assignment answer.
Straight forward and readily understood solutions, on the other hand, are fodder for student copying without any real understanding.
참고 항목
카테고리
Help Center 및 File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!