0
$\begingroup$

In a multistep code, I am trying to use module to define a function such that (working example)

CR[i_] := {{i*5, 3, 5, i, 2 i, 5 i}, {1, 2, 3, 4, 5, 6}}

A[EF_] := Module[{cr = CR[EF]}, c[t_] = ParallelTable[cr[[t, m]], {m, 1, 6}]; {c[1], c[2]}]

A[1]

by using this expression, I am getting my o/p in about 14 secs. However, along with the o/p, there also comes an error message 'Part::pkspec1: The expression t$ cannot be used as a part specification.'

But, when I replace equal to (=) by set delayed (:=) in the definition of c[t], error message is gone, but I get my o/p in about 4 minutes instead of 14 secs.

So, my question is how to go about it..so that I get my o/p in reasonable time, but without any error message. Will appreciate any suggestion.

$\endgroup$
0

1 Answer 1

2
$\begingroup$

There are few problems with your code.

First, I guess that A[r] and B[r] are some nested constructs. In the simplest case, lists. Is it right?

If yes, let us for the sake of example take the following:

A[r_] := {r, r^2, r^3, r^4};
B[r_] := {r^2, r^3, r^4, r^5};

Second, you cannot define c[t] as a function of t in your code, since t is a dummy variable. Therefore, c is not a function of t but a constant. I would define it as follows:

c = Table[a[[t]] + b[[t]], {t, 1, 4}];

Third, the use of the ParallelTableonly pays off if the table is very long or the evaluation of its components is very time-consuming, or both. Otherwise, its use makes the evaluation considerably longer. For this reason, I used Table instead. If you have a good reason to use the ParallelTable in your code, you may replace one with another.

Fourth, you need to use a semicolon (;) after each operator entering the Module except for the last one.

Fifth, as soon as c cannot be defined as the function of t the c[t] statement staying at the end of the Modulehas no sense.

With all these notes one finds this:

 AA[r_] = Module[{a = A[r], b = B[r]}, 
      c = Table[a[[t]] + b[[t]], {t, 1, 4}]; c]

(*    {r + r^2, r^2 + r^3, r^3 + r^4, r^4 + r^5}   *)

and, say,

AA[2]

(*  {6, 12, 24, 48}  *)

Think also, if it is better to define AA[r] using Setor SetDelayed?

Have fun!

$\endgroup$
2
  • $\begingroup$ Now, I have added a working example in the original post. It explains my problem better. Thanks $\endgroup$
    – user49535
    Sep 7, 2021 at 11:52
  • $\begingroup$ In this case, your problem is solved by a more economical code: c[z_] := Take[CR[i], {z}] // Flatten Check c[1] and c[2]. $\endgroup$ Sep 7, 2021 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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