0
$\begingroup$

In this question, it was mentioned that one can output the concatenation of a string and a variable by using StringForm[]:

var1 = "Tree";
var2 = 10;

StringForm["The `1` is about `2` feet tall...", var1, var2]

(* "The Tree is about 10 feet tall..." *)

This works. However, when I try to use it within a loop, I get no output whatsoever:

For[i = 1, i < 10, i++,
(
   var1 = "Tree";
   var2 = 10;

   StringForm["The `1` is about `2` feet tall...", var1, var2]
)]

I don't understand why there is no output here as I am just repeating the same operation $i$ times. What am I missing?


EDIT: The aim is to perform a task within the For loop, and print some intermediary results every $n$ iterations.

$\endgroup$
8
  • $\begingroup$ Use Table. For does not return anything. $\endgroup$
    – Kuba
    Oct 26, 2018 at 12:45
  • $\begingroup$ @Kuba Thank you for your comment. What about the case where a bunch of operations are being executed within the For loop, and some intermediary results must be printed out every $n$ iterations? $\endgroup$
    – Klangen
    Oct 26, 2018 at 12:46
  • $\begingroup$ Only printed or collected? Use Print or for the latter case Sow/Reap. At the end you can have Table to manage your loop and Table[proc; string, {i, 10}] or something. Assuming string generation is the last step only. $\endgroup$
    – Kuba
    Oct 26, 2018 at 12:48
  • $\begingroup$ Thank you. I will try to use Table. In the meantime, can you please explain why a perfectly valid output does not output when placed within a For loop? As a software developer, this makes no sense to me. $\endgroup$
    – Klangen
    Oct 26, 2018 at 12:56
  • 2
    $\begingroup$ For evaluates expression in a loop but does not return anything. Here's more about that: mathematica.stackexchange.com/a/124077/5478 $\endgroup$
    – Kuba
    Oct 26, 2018 at 13:00

0

Browse other questions tagged or ask your own question.