While introducing Arrays, I want to explain the difference in Julia between a normal column vector and a matrix with a single column… Is there a way to create a one-column matrix like b = collect([1 2 3]')
in a simpler way (and without using rand, zeros, the Array constructor with undef/nothing…) ?
reshape([1:3;],3,1)
Or even
reshape([1:3;], :, 1)
if you do not want to care about number of elements.
There is no way to create it with just using the brackets syntax without introducing other functions, including reshape ?
[ i for i=1:3, j=1:1]
but it is not compact.
FYI, probably still not what you looking for though.
[1:3 1:3][:, [1]]
Matrix{Float64}(undef, 3, 1)
Does that work for you?
normally I write hcat(1:3)
Or maybe fill(0,(3,1))
.
yeah, thanks everyone, I think the answer is that it is not possible to use some simple a = [1 ; 2 ; 3 ;]
like syntax to create a one-column matrix, as it is reinterpreted as a column vector… I’ll use one of the methods you posted, it is just that they all use already some other concepts…
a=[1 2 3]'
[1, 2, 3][:,:]
3×1 Matrix{Int64}:
1
2
3
And if @DNF was online, he would likely suggest:
permutedims([1 2 3])
The limitation is that in bracket notation a space is used to indicate hcat
and it is ignored if you have only one argument passed.
One wouldn’t recommend this, but it is interesting:
using LinearAlgebra
julia> [1, 2, 3]*I
3×1 Matrix{Int64}:
1
2
3
Note that there is a PR Syntax for multidimensional arrays by BioTurboNick · Pull Request #33697 · JuliaLang/julia · GitHub, which, if I understand it correctly, means that a = [1 ; 2 ; 3 ;;]
may be a future syntax for this. Specifically see the proposed NEWS
entry.
I thought a Vector was a synonym for a 1 Column Matrix? Why would there be a need to differentiate?
There are many reasons, e.g.:
- they have different
ndims
- you can resize
Vector
, but you cannot resizeMatrix
- there are functions that accept only
Vector
or onlyMatrix
(especially inLinearAlgebra
) - Tables.jl tables usually require
AbstractVector
, but disallow 1-columnAbstractMatrix
as columns
Mathematically they are the same, but they are different objects in Julia. [1,2,3]
is a uni-dimensional array, collect([1 2 3]')
is a two- dimensional array where “it happens” that the second dimension has size 1, i.e. there is only one column. So, if a function requires AbstractArray{T,1}
the first will fit, but the second will not.
Note that this possible confusion doesn’t arise with row vectors, as all row vectors in Julia have 2 dimensions.
You can also use
Matrix([1,2,3]')
if that’s clearer than collect
@tomerarnon, you probably meant:
Matrix([1 2 3]')
3×1 Matrix{Int64}: