How can I draw these rectangles in a loop using psychtoolbox... there must be a better way than what I've done. Thanks for your help!!

7 views (last 30 days)
% Draw base rectangle
r1=[0 0 20 20];
r2=OffsetRect(r1, 200,200);
r3=OffsetRect(r1, 200,235);
r4=OffsetRect(r1, 235,200);
r5=OffsetRect(r1, 235,235);
r6=OffsetRect(r1, 300,235);
r7=OffsetRect(r1, 300,200);
r8=OffsetRect(r1, 335,200);
r9=OffsetRect(r1, 335,235);
r10=OffsetRect(r1, 200,100);
r11=OffsetRect(r1, 200,135);
r12=OffsetRect(r1, 235,100);
r13=OffsetRect(r1, 235,135);
r14=OffsetRect(r1, 300,100);
r15=OffsetRect(r1, 300,135);
r16=OffsetRect(r1, 335,100);
r17=OffsetRect(r1, 335,135);
Screen('FillRect',win, [0, 0, 1], r2);
Screen('FillRect',win, [0, 0, 1], r3);
Screen('FillRect',win, [0, 0, 1], r4);
Screen('FillRect',win, [0, 0, 1], r5);
Screen('FillRect',win, [0, 0, 1], r6);
Screen('FillRect',win, [0, 0, 1], r7);
Screen('FillRect',win, [0, 0, 1], r8);
Screen('FillRect',win, [0, 0, 1], r9);
Screen('FillRect',win, [0, 0, 1], r10);
Screen('FillRect',win, [0, 0, 1], r11);
Screen('FillRect',win, [0, 0, 1], r12);
Screen('FillRect',win, [0, 0, 1], r13);
Screen('FillRect',win, [0, 0, 1], r14);
Screen('FillRect',win, [0, 0, 1], r15);
Screen('FillRect',win, [0, 0, 1], r16);
Screen('FillRect',win, [0, 0, 1], r17);
% Show it on the display:
Screen('Flip', win);

Accepted Answer

Jeff Miller
Jeff Miller on 8 Nov 2018
One simple improvement is to make r a cell array. Add a command at the top like
r=cell(17,1);
Then, instead of commands like
r2=OffsetRect(r1, 200,200);
you would use
r{2}=OffsetRect(r{1}, 200,200);
Then, at the end, you could draw all the rectangles with 3 lines:
for i=2:17
Screen('FillRect',win, [0, 0, 1], r{i});
end
Screen('flip');
I'm sure you could do even better by working out a pattern to compute the various values of r, 2-17, but I'm not sure that would be worth the effort.

More Answers (1)

Olivia Krieger
Olivia Krieger on 8 Nov 2018
Thank you for your help! I would also like to compute a pattern (the computation I'm not worried about, but figuring out how to implement it is where I'm a little stuck.) I will have 64 squares total (which will most often be in the same position), however some boxes will change position. So I think it will be worthwhile for me to implement a pattern (at least for the main pattern).
  2 Comments
Jeff Miller
Jeff Miller on 8 Nov 2018
There would be be many different ways to do this, and it is tough to say which one will be most convenient without studying your full pattern in detail. But you will probably want to use some kind of loop like this:
for i=2:17
newx = ???; % compute values here depending on your pattern.
newy = ???; % You will need 'if' statements if the values depend on i.
r{i}=OffsetRect(r1, newx,newy);
end

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!