I have the following matrix A = [1.00 2.00; 3.00 4.00]
and I need to convert it into a vector of Vectors as follows:
A1 = [1.00; 3.00]
A2 = [2.00; 4.00]
Any ideas?
I have the following matrix A = [1.00 2.00; 3.00 4.00]
and I need to convert it into a vector of Vectors as follows:
A1 = [1.00; 3.00]
A2 = [2.00; 4.00]
Any ideas?
tl;dr
This can be very elegantly created with a list comprehension:
A = [A[:,i] for i in 1:size(A,2)]
This essentially converts A
from something that would be indexed as A[1,2]
to something that would be indexed as A[2][1]
, which is what you asked.
Here I'm assigning directly back to A
, which seems to me what you had in mind. But, only do this if the code is unambiguous! It's generally not a good idea to have same-named variables that represent different things at different points in the code.
NOTE: if this reversal of row / column order in the indexing isn't the order you had in mind, and you'd prefer A[1,2]
to be indexed as A[1][2]
, then perform your list comprehension 'per row' instead, i.e.
A = [A[i,:] for i in 1:size(A,1)]
It's even simpler.
eachcol
is all you need. It's an abstract vector.
A=eachcol(A)
Now A[1]
is [1.00; 3.00]
, and A[2]
is [2.00; 4.00]
.
With this approach, there are no memory allocations. Everything is based on views.
Another option is B = [eachcol(A)...]
. This returns an variable with type Vector{SubArray}
which might be fine depending on what you want to do. To get a Vector{Vector{Float64}}
try,
B = Vector{eltype(A)}[eachcol(A)...]
It would be much better simply to use slices of your matrix i.e. instead of A1 use
A[:,1]
and instead of A2 use
A[:,2]
If you really need them to be "seperate" objections you could try creating a cell array like so:
myfirstcell = cell(size(A,2))
for i in 1:size(A,2)
myfirstcell[i] = A[:,i]
end
See http://docs.julialang.org/en/release-0.4/stdlib/arrays/#Base.cell
(Cell arrays allow several different types of object to be stored in the same array)
cell
A_vec = Array{Array{eltype(A),1}, size(A,2)}
–
Adjunct © 2022 - 2024 — McMap. All rights reserved.
sub()
, e.g.B = sub(A, 1:size(A,2),1)
. – Adjunct