2
$\begingroup$

In this contribution Leonid Shifrin says that

You can not really use indexed variables in Compile, although it may appear that you can.

This sounds ambiguous to me. Is it possible or is it not possible? And if the former is true, how to implement indexed variables in compile? This would simplify one of my programs a lot.

$\endgroup$
  • 1
    $\begingroup$ I'm afraid this is a bit too board, can you add a specific example? $\endgroup$ – xzczd Oct 15 '18 at 14:41
  • $\begingroup$ It's just the idea to generate something like Table[var[i],{i,1,10}] within Compile and then assign values to the different var[i]. That's what I mean about indexed variables. Sorry for the confusion. $\endgroup$ – Display Name Oct 15 '18 at 14:44
  • 3
    $\begingroup$ I don't remember exactly, but I think what I meant was that while you can compile this: Compile[{{x[1], _Integer}, {y[1], _Integer}}, x[1] + y[1]] down to MVM byte code or C just fine, the following, for example: Compile[{{a, _Integer}, {b, _Integer}}, Module[{x}, x[1] = a; x[2] = b; x[1] + x[2]]], will use the calls to main evaluator. You can see that by loading Get["CompiledFunctionTools`"] and calling CompilePrint on resulting CompiledFunctions. $\endgroup$ – Leonid Shifrin Oct 15 '18 at 14:57
  • $\begingroup$ If I understand your question correctly, I think we can achieve something similar with the help of code-generation technique e.g. here. But it's hard to help without a complete example, so once again, please be more specific. BTW, another related post is this. $\endgroup$ – xzczd Oct 15 '18 at 14:59
  • $\begingroup$ @LeonidShifrin: Yes, this is exactly the problem I was referring to. Would have been great to use these kind of indexed variables without explicitely specifying them which doesn't seem to be possible then. But I like Henrik Schumacher's workaround. Thank you for the links xzczd! $\endgroup$ – Display Name Oct 15 '18 at 19:13
4
$\begingroup$

Well, one can use arrays to emulate indexed variables. As an example I do something which is usually verboten: I use Subscript (but in a controlled environment):

cf = With[{Subscript = Part},
  Compile[{{a, _Integer}, {b, _Integer}}, 
   Block[{x},
    x = Table[0, 2];
    Subscript[x, 1] = a;
    Subscript[x, 2] = b;
    Subscript[x, 1] + Subscript[x, 2]
    ]
   ]
  ];

Now,

CompiledFunctionTools`CompilePrint[cf]

shows that this compiles nicely without calls to MainEvaluate...

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.