Jiayan Yang
Jiayan Yang

Reputation: 101

How to convert array to matrix in Julia

I want to pick col of A(5*7) whose index is in C and calculate its inverse. However the B here is 5*1 array rather than a square matrix. How can I achieve it?

A = [1 2 1 0 0 0 0;
    1/3 1 0 1 0 0 0;
     4  1 0 0 1 0 0;
     -4 2 0 0 0 1 0;
     -6 2 0 0 0 0 1]
C = [3 4 5 6 7]'

B = [A[:,i] for i in C]
x = inv(B)*b

Upvotes: 2

Views: 1560

Answers (2)

Ultima Ratio
Ultima Ratio

Reputation: 151

  1. b ist not defined. What is it?
  2. The B works by a vector of the slice intended: C = vec([3 4 5 6 7])
  3. then create a 5x5 Array with the dimensions 5x5: B = [A[y,i] for i in C,y in 1:5]
  4. inverse the matrix B (which is identical to itsself in this example) multiplied by (small) b should work. my REPL:
julia> B = [A[y,i] for i in C,y in 1:5]
5×5 Array{Float64,2}:
 1.0  0.0  0.0  0.0  0.0
 0.0  1.0  0.0  0.0  0.0
 0.0  0.0  1.0  0.0  0.0
 0.0  0.0  0.0  1.0  0.0
 0.0  0.0  0.0  0.0  1.0

julia> x=inv(B)
5×5 Array{Float64,2}:
 1.0  0.0  0.0  0.0  0.0
 0.0  1.0  0.0  0.0  0.0
 0.0  0.0  1.0  0.0  0.0
 0.0  0.0  0.0  1.0  0.0
 0.0  0.0  0.0  0.0  1.0

Upvotes: 1

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69949

Alternatively to what Ultima Ratio suggests you can simply write:

B = A[:, C]

(for this to work C should be a column vector)

Additionally in this case it would be better to simply define C as:

C = 3:7

or

C = [3,4,5,6,7]

EDIT: In your code:

C = [3 4 5 6 7]'

is a 5x1 matrix not a vector. In order to convert it to a vector write vec(C). So A[:, vec(C)] will give you a matrix.

Upvotes: 4

Related Questions