Message Boards Message Boards

How do I get the Graphics command to work inside a Do loop?

Posted 10 years ago

In the code below, I define the symbol "drawCommand" to draw a white square with a black border and then a symbol "printCommand" to print a value. These work as expected until put inside a Do loop. Then the printCommand executes but drawCommand doesn't. The output can be seen in the attached .pdf file.
Can anyone tell me how to get this to work?
Much obliged, larry.c

border = Rectangle[{-1, -1}, {1, 1}];
drawCommand := Graphics[{EdgeForm[Thick], White, border}];
drawCommand 

timeValue = "global value";
printCommand := Print["   timeValue = ", timeValue ];
printCommand

Print["Begin Loop"];
Do[drawCommand; printCommand  , {timeValue , 0, 01., .2}]
Print["End Loop"];

drawCommand 
printCommand
Attachments:
POSTED BY: Larry Cuba
3 Replies

First question, yes:

graphics = {}
Do[graphics=Append[graphics,drawCommand],{timeValue,0,01.,.2}]
graphics

An alternative formation might also be

 Table[drawCommand, {t, 0, 1, .2}]

To the second question, it might help to know a little bit more about the language. Everything in the Wolfram Language is a function call, including loops like Do and While. This is very different than a language like C where a Do loop is purely about controlling the flow of commands.

The side effect of this is that all commands define their own output. Thus you need to look at the documentation of each command. Print is a bit weird in that it prints to standard out, but does not produce an Out[n] value:

In

1

In

Mostly, I would avoid Print statements accept for very low level debugging and creating logfiles from Mathematica scripts.

POSTED BY: Jason Grigsby

Print and Graphics interact with the front end differently. Print writes to standard out whereas Graphics produces possible output. The Do loop withholds output from its first argument. Try the following:

drawn = ConstantArray[Null, 5]

Do[drawn[[iter]] = drawCommand, {iter, 1, 5}]

drawn
POSTED BY: Jason Grigsby
Posted 10 years ago

Thanks, Jason.

Is there a way to achieve this by Appending to a list instead of using a fixed length array? I don't know how large an array I will ultimately need in my actual application.

Also, is there somewhere in the documentation that explains these concepts of "Graphics produces possible output" and "Do loop withholds output"?

They're new to me.

Thanks again for your help.

POSTED BY: Larry Cuba
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract