1
$\begingroup$

There are a several variables a11, a12, a13,...,a21, a22, a23,... The standard output of these variables on the screen is as follows: Print[" a11= ", a11, " a12= ", a12, ...]

Is it possible to somehow automate (use a loop for example) the writing of all these variables to the Print function?

$\endgroup$
3
  • $\begingroup$ Instead of using a11,12,... and so on, why not just use a[1,1] a[1,2], ... ? Also you could use a list of lists (matrix) a = {{...}, {...}, {...}, ...}? $\endgroup$
    – flinty
    May 20 at 13:28
  • $\begingroup$ @flinty, it is not very clear how to manipulate such constructs a[1,1] a[1,2], ... inside a function $\endgroup$
    – Mam Mam
    May 20 at 13:31
  • $\begingroup$ ... what do you mean 'not very clear'? It's a lot easier than using symbols like you have, surely? $\endgroup$
    – flinty
    May 20 at 13:32

2 Answers 2

2
$\begingroup$

Create some variables

Table[Set[Evaluate[ToExpression["a" <> ToString[n] <> ToString[m]]], 
  RandomReal[]], {n, 1, 5}, {m, 1, 5}]

Mathematica graphics

Now prints them all

vars = Flatten@Table["a" <> ToString[n] <> ToString[m], {n, 1, 5}, {m, 1, 5}];
Row[{#, "=", ToExpression[#]}] & /@ vars

Mathematica graphics

$\endgroup$
4
$\begingroup$

You simply don't want to do this:

f[a[1,3]_,a[5,2]_]:=a[1,3] + a[5,2]

I don't mean because it's not syntactically correct, I mean that it doesn't make any sense as a function definition. When you define a function with formal arguments, you don't want to add overly specific semantics to your variables. For example, you'd never define a function that computes the area of a circle like this:

circleArea[radius16_] := Pi * radius16^2

The "16" bit just has nothing to do with the radius or circles or area or anything. It's a distraction.

So, in

f[a[1,3]_,a[5,2]_]:=a[1,3] + a[5,2]

the indices 1,3 in a[1,3] can't possibly mean anything. As they are used in the right hand side, a[1,3] + a[5,2], they are just formal arguments.

On the other hand, if what you're trying to do is really to index into something, then the indices do mean something. Let's say I have

a = {{1, 2}, {3, 4}}

and I want to define a function that adds the diagonal values. I could do this:

f[x_] := x[[1, 1]] + x[[2, 2]]
f[a]
(* 5 *)

Now those indices mean something, but the argument x is still just a formal argument that is expected to represent a 2x2 matrix. (You could enforce and check that it is a matrix, but I haven't shown that.)

And now you can send your individual values to the Print function like this:

Scan[Print, a, {2}]
$\endgroup$

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.