Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transpose array of strings in Julia?

Tags:

julia

It works with numbers but not with strings.

The [1 2]' works but the ["a" "b"]' doesn't.

Why? And how to do that?

like image 219
Alex Craft Avatar asked Feb 27 '20 23:02

Alex Craft


3 Answers

Why?

["a" "b"]' does not work because the ' operator actually computes the (lazy) adjoint of your matrix. Note that, as stated in the documentation, adjoint is recursive:

Base.adjointFunction

adjoint(A)

Lazy adjoint (conjugate transposition) (also postfix '). Note that adjoint is applied recursively to elements.

This operation is intended for linear algebra usage - for general data manipulation see permutedims.

What happens in the case of [1 2] is that adjoint does not only flip elements across the diagonal; it also recursively calls itself on each element to conjugate it. Since conjugation is not defined for strings, this fails in the case of ["a" "b"].


How?

As suggested by the documentation, use permutedims for general data manipulation:

julia> permutedims(["a" "b"])
2×1 Array{String,2}:
 "a"
 "b"
like image 168
François Févotte Avatar answered Nov 01 '22 05:11

François Févotte


Transposing is normally for linear algebra operations but in your case the easiest thing is just to drop the dimension:

julia> a = ["a" "b"]
1×2 Array{String,2}:
 "a"  "b"

julia> a[:]
2-element Array{String,1}:
 "a"
 "b"
like image 27
Przemyslaw Szufel Avatar answered Nov 01 '22 05:11

Przemyslaw Szufel


If the string matrix is created by a literal, the easiest way is to create a vector immediately instead of a matrix.

["a", "b"]
like image 33
Fredrik Bagge Avatar answered Nov 01 '22 07:11

Fredrik Bagge