Mathematica Mathematica - Constructing Matrices

AI Thread Summary
The discussion focuses on constructing a specific matrix with alternating values based on a given size, n. For n = 8, the desired matrix format is [16 -16 16 -16 16 -16 16 -16]. Participants suggest using anonymous functions in Mathematica to achieve this, with examples like Array[2 n (-1)^(# - 1) &, {n}] and defining a named function f[n_][x_] := 2 n (-1)^(x-1). Alternatives include using Block and Table to create the matrix, with options for both 1 by n and n by 1 formats. The use of (-1)^(# - 1) is explained as a way to alternate signs, and users are encouraged to explore the documentation on Pure Functions for further understanding.
sugaku
Messages
16
Reaction score
0
Good day to all,

I am stuck with this. I am trying to construct a matrices with this properties...

if n = 8, suppose the matrix with size 1 by 8 become
[16 -16 16 -16 16 -16 16 -16]

if n the matrix become [2n -2n 2n -2n 2n -2n 2n -2n ] with size 1 by n

I do appreciate if someone could give me hint on this... thank you in advance
 
Physics news on Phys.org
Something like
With[{n = 8}, Array[2 n (-1)^(# - 1) &, {n}]]

nb the above uses anonymous function notation: eg
#^2& = Function[x, x^2]
 
Simon_Tyler said:
Something like
With[{n = 8}, Array[2 n (-1)^(# - 1) &, {n}]]

nb the above uses anonymous function notation: eg
#^2& = Function[x, x^2]

Thank you so much for your help. I do appreciate it. I am not familiar yet with the usage of (-1)^(# - 1)
 
Not a prob.

I thought you might not be familiar with anom functions, which is why I gave its full mma name: Function. You can look it up in the documentation center - and read the tutorial on Pure Functions (tutorial/PureFunctions).

An equivalent solution where we give the function a name is
f[n_][x_] := 2 n (-1)^(x-1)
Array[f[8], {8}]
 
If you want a n x 1 matrix, you can also simply do

Code:
Block[{n = 8},
Table[(-1)^j * 2n, {j, 1, n}
]
or

Code:
Block[{n = 8},
Transpose[Table[(-1)^j * 2n, {j, 1, n}]]
]

(apply MatrixForm to see which way it comes out correctly)
 

Similar threads

Replies
4
Views
2K
Replies
3
Views
3K
Replies
4
Views
2K
Replies
2
Views
1K
Replies
10
Views
12K
Replies
13
Views
3K
Back
Top