I have a 3 dimensional array
x = rand(6,6,2^10)
I want to multiply each matrix along the third dimension by a vector. Is there a more clean way to do this than:
y = rand(6,1)
z = zeros(6,1,2^10)
for i in 1:2^10
z[:,:,i] = x[:,:,i] * y
end
Overview. In Julia, we can do matrix multiplication on two variables with a Matrix data type. We can use the asterisk ( * ) operator for this purpose.
Get array dimensions and size of a dimension in Julia – size() Method. The size() is an inbuilt function in julia which is used to return a tuple containing the dimensions of the specified array. This returned tuple format is (a, b, c) where a is the rows, b is the columns and c is the height of the array.
Julia provides a very simple notation to create matrices. A matrix can be created using the following notation: A = [1 2 3; 4 5 6]. Spaces separate entries in a row and semicolons separate rows. We can also get the size of a matrix using size(A).
To show how many rows and columns a matrix has we often write rows×columns. When we do multiplication: The number of columns of the 1st matrix must equal the number of rows of the 2nd matrix. And the result will have the same number of rows as the 1st matrix, and the same number of columns as the 2nd matrix.
If you are working with matrices, it may be appropriate to consider x
as a vector of matrices instead of a 3D array. Then you could do
x = [rand(6,6) for _ in 1:2^10]
y = [rand(6)]
z = x .* y
z
is now a vector of vectors.
And if z
is preallocated, that would be
z .= x .* y
And, if you want it really fast, use vectors of StaticArrays
using StaticArrays
x = [@SMatrix rand(6, 6) for _ in 1:2^10]
y = [@SVector rand(6)]
z = x .* y
That's showing a 10x speedup on my computer, running in 12us.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With