Getting several errors and bad output.
조회 수: 1 (최근 30일)
이전 댓글 표시
So the idea is I have this turtle. The turtle receives these commands R, L or F. (Right, Left, Forward)
If it's right, it turns 60 degrees clockwise, if it's left it turns counter clockwise. If it's F it moves forward one unit. The commands are coming from a recursion program I wrote to plot a snowflake.
This program, is supposed to output the coordinates after every time the turtle moves forward, but not when it turns left or right. I'm really stuck here. Can't figure out what's wrong. Not even sure if I get close to the outputs. Any help guys????!?!? Thanks so much!!!
function [ coords ] = myKochPts( commands )
theta = 0;
dim = 1;
pos = [0 0];
for i = 1:length(commands)
if commands(i) == 'F'
dim = dim + 1;
end
end
coords = zeros(dim,2);
for j = 1:length(commands)
for k =1:length(commands)
if commands(j) == 'L'
theta = myLeft(theta);
elseif commands(j) == 'R'
theta = myRight(theta);
else
pos = myForward(pos,theta);
coords(k,1) = pos(1);
coords(j,2) = pos(2);
end
end
end
end
function [ newPos] = myForward(curPos,curTheta)
origin = [0,0];
newPos = origin + [(curPos(1) + cos(curTheta)) , (curPos(2) +sin(curTheta))];
end
function [ newTheta ] = myLeft( curTheta)
newTheta = curTheta + pi/3;
end
function [ newTheta ] = myRight( curTheta)
newTheta = curTheta - (pi/3);
end
댓글 수: 2
Star Strider
2014년 2월 22일
I’m not sure what you’re doing. It seems it never actually goes anywhere except forward in a straight line. It simply rotates left or right otherwise, but doesn’t move.
Shouldn’t the coordinate updates for myLeft and myRight be something similar to myForward?
답변 (2개)
Walter Roberson
2014년 2월 22일
Your mistake is in
coords(k,1) = pos(1);
coords(j,2) = pos(2);
The two first indices should be the same, and should reflect how many F commands have been found so far in the string.
You do not need a double-nested loop: you can do the processing in a single pass.
댓글 수: 5
Walter Roberson
2014년 2월 22일
When you eliminated the double loop in favour of a single loop, which loop variable did you use?
coords(k,:) = myForward(pos,theta);
should work if it was "k" that is being used as the counter of the number of F commands found so far. Remember to increment whichever counter it is you use.
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!