need help to write a program to draw the rectangle decrived down below.

29 次查看(过去 30 天)
rect1.x = 30; % x-coordinate of the lower left corner
rect1.y = 30; % y-coordinate of the lower left corner
rect1.width = 500;
rect1.height= 400;
rect1.color = 'b';
% Rectangle 2
rect2.x = 350; % x-coordinate of the lower left corner
rect2.y = 300; % y-coordinate of the lower left corner
rect2.width = 220;
rect2.height= 250;
rect2.color = 'r';
% Rectangle 3
rect3.x = 300; % x-coordinate of the lower left corner
rect3.y = 250; % y-coordinate of the lower left corner
rect3.width = 150;
rect3.height= 400;
rect3.color = 'c';
rect1.x = 30; % x-coordinate of the lower left corner
rect1.y = 30; % y-coordinate of the lower left corner
rect1.width = 500;
rect1.height= 400;
rect1.color = 'b';
% Rectangle 2
rect2.x = 350; % x-coordinate of the lower left corner
rect2.y = 300; % y-coordinate of the lower left corner
rect2.width = 220;
rect2.height= 250;
rect2.color = 'r';
% Rectangle 3
rect3.x = 300; % x-coordinate of the lower left corner
rect3.y = 250; % y-coordinate of the lower left corner
rect3.width = 150;
rect3.height= 400;
rect3.color = 'c';

回答(1 个)

Ameer Hamza
Ameer Hamza 2020-5-8
编辑:Ameer Hamza 2020-5-8
Always use an array instead of naming the variable like rect1, rect2, .... It makes the code much simpler. Following code draw rectangles using patches
rect(1).x = 30; % x-coordinate of the lower left corner
rect(1).y = 30; % y-coordinate of the lower left corner
rect(1).width = 500;
rect(1).height= 400;
rect(1).color = 'b';
% Rectangle 2
rect(2).x = 350; % x-coordinate of the lower left corner
rect(2).y = 300; % y-coordinate of the lower left corner
rect(2).width = 220;
rect(2).height= 250;
rect(2).color = 'r';
% Rectangle 3
rect(3).x = 300; % x-coordinate of the lower left corner
rect(3).y = 250; % y-coordinate of the lower left corner
rect(3).width = 150;
rect(3).height= 400;
rect(3).color = 'c';
figure;
axes();
hold on
for i=1:numel(rect)
r = rect(i);
rect_x = [r.x r.x+r.width r.x+r.width r.x];
rect_y = [r.y r.y r.y+r.height r.y+r.height];
patch(rect_x, rect_y, r.color);
end

类别

Help CenterFile Exchange 中查找有关 Surface and Mesh Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by