I need to create a script in MATLAB that will look similar to this:

But the code I have is not working, and it is giving me the inverse, in that, the squares grow in size rather than shrink.
x = [0 0 2 2];
y = [0 2 2 0];
fill(x,y,'r');
hold on
for i = 1:10
x = [(x(3)) (x(3)) (x(3)/2) (x(3)/2)];
y = [(y(3)) (y(2)/2) (y(2)/2) (y(3))];
fill(x,y,'r');
end
Please provide an explanation along with the answer as I want to learn what I did wrong.
Have a look at the two values of
xalone to simplify this investigation. After your first iteration,xwill be2and1, in the second iteration1and0.5. This means you are approaching zero with squares that are getting smaller and smaller, the opposite of what you intended to do.How about you start big close to the origin and shrink as you go further away? You could initialize
x = [0, 2];andy = [0, 2];. We’re using only two elements here because for a square that’s aligned with your axes, that’s all we need. The first iteration may start with a shift by the edge length of the previous square as inx = x + x(2) - x(1);. The square will have to shrink though as well, so you could move the left corners by some small fraction of the edge length, e.g.x(1) = x(1) + (x(2) - x(1)) * 0.1;. To summarize, your loop would look likeNote that we replaced
x(2) - x(1)byedge_len. Then we another problem of setting your color. You could use a color vectorc = [1, k / 10, k / 10]to create a gradient from red to almost white. Then instead offill(..., 'r');you’d usefill(..., c);With this, there won’t be any
filloutside the loop. That used to cover all your interesting graphing in the code block you show in the question.