Getting several errors and bad output.
4 ビュー (過去 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!