Help with error and coding.

1 view (last 30 days)
Steven Lam
Steven Lam on 11 Nov 2017
Edited: Mischa Kim on 11 Nov 2017
clc
clear variables
close all
fid=fopen('hw3_task2.txt','r');
hr_deg=[60 30 0 330 300 270 240 210 180 150 120 90];
k=1;
x_start=fscanf(fid,'%f',1);
y_start=fscanf(fid,'%f',1);
x_s=fscanf(fid,'%f',1);
y_s=fscanf(fid,'%f',1);
while k<=24
dist(k)=fscanf(fid,'%f',1);
deg(k)=fscanf(fid,'%f',1);
D(k)=fscanf(fid,'%f',1);
S(k)=fscanf(fid,'%f',1);
k=k+1;
end
x_c=[x_start];
y_c=[y_start];
k=1;
while k<=24
x_c(k+1)=dist(k)*cosd(hr_deg(deg(k)));
y_c(k+1)=dist(k)*sind(hr_deg(deg(k)));
k=k+1;
end
k=1;
hold on
x=x_c(1);
y=y_c(1);
hold on
plot(x,y,'go')
text(x,y,'Start')
while k<=25
x(k+1)=x(k)+x_c(k+1);
y(k+1)=y(k)+y_c(k+1);
plot([x(k) x(k+1)], [y(k) y(k+1)], 'b*-')
k=k+1;
end
k=1;
while k<=24
if (s(k)==1)
plot(x(k+1),y(k+1),'bd')
end
if (d(k)==1)
plot(x(k+1),y(k+1),'ms')
end
k=k+1;
end
plot(x(k),y(k),'g*')
text(x(k),y(k),'End')
grid on
xlabel('X Position')
ylabel('Y Position')
title('Robot Task 2')
axis([1 100 1 100]);
fclose(fid)
I am trying to produce the graph below with loops. It keeps giving me the error:
Index exceeds matrix dimensions.
Error in slam42Part2 (line 44)
x(k+1)=x(k)+x_c(k+1);
How do I fix this error and also does anyone know a way to code a loop to where it plots the squares or diamonds or both at certain points? I noticed that there is a pattern but I am having trouble coding it. The first row of the data is just the starting point. The first column is the distance from the previous point and the second column after the first row is the direction (clock-wise for example 12 o clock is 90 degrees.) The third column is just a value for the diamond. 1= there is a diamond and 0=there is no diamond. The 4th column is the same as the 3rd column except it is for squares instead of diamonds.

Answers (1)

Mischa Kim
Mischa Kim on 11 Nov 2017
Edited: Mischa Kim on 11 Nov 2017
One thing I noticed is the following: in your second while-loop you have
while k<=24
x_c(k+1)=dist(k)*cosd(hr_deg(deg(k)));
so x_c has 25 elements. However, in the following while-loop you have
while k<=25 % should this be k<=24?
x(k+1)=x(k)+x_c(k+1);
For k=25 you are trying to access x_c(25+1) which is not defined because x_c has only 25 elements.
Hope that helps.

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!