Reputation: 11
width=50;
height=30;
level=42;
triangles=10;
function sq = create_square(width, height, level, triangles)
sq(1,:)=[0 level];
count=2;
for i=1:triangle
sq(count,:)=[i*width level];
sq(count+1,:)=[i*(width/2) level-height];
sq(count+2,:)=[(i-1)*(width) level];
count=count+3;
end
function plot_objects_2d( object, col )
hold on;
plot( object(2:end,1), object(2:end,2), col, 'LineWidth', 1.5 );
hold off;
function display_image( im )
image( im(end:-1:1,:,:) ); % flip image
axis image;
set(gca, 'ydir', 'normal'); % flip axis
h = gca;
axis on;
I'm trying to draw a line of upsidedown triangles on the bottom portion of the y axis and after the first triangle, which is fine, the next ones divide the width of all of the triangles instead of just the new triangle. Does anyone know why this is?
Upvotes: 0
Views: 88
Reputation: 7817
In a case like this think you need to define what sequence of points you are trying to get (hand calculate say for the first three triangles), then think through what your loop is doing.
For any given i:
The first point you calculate is at i*width
The second point you calculate is at i*width/2
The third point is at (i-1)*width
.
The difference between the first and third points will be width
and is independent of i
. However, the difference between the first and second points is i*width/2
.
If you want the 2nd point to be equally spaced between the third and first (e.g. always differs by width/2
), then you need to do something like:
sq(count+1,:)=[i*width-width/2 level-height];
A general note, not that it makes a huge difference in this case - you don't really need loops here.
sq = zeros(1+triangles*3,2);
%y values
sq(:,2) = level; % mostly this
sq(3:3:end,2) = level-height; % fill in the others
%x values
sq(2:3:end,1)=width*(1:triangles);
sq(3:3:end,1)=width*(1:triangles)-width/2;
sq(4:3:end,1)=width*(0:triangles-1);;
Upvotes: 1