Search code examples
juliamatrix-multiplication

Julia throwing matrix multiplication error when matrix dimensions are correct


I am trying to multiply a 1000x1000 matrix with a 1000x2 matrix. However, I keep getting an error that the dimensions of the matrices are incorrect. I am brand new to Julia and am not sure what the issue is exactly, so any help would be great. Upon further inspection it seems like it is related to my use of rand command, but I'm not sure how to get it to output the matrix with the dimensions I'm looking for. I have commented on the line that is causing the issue, and commenting on the rand lines as well in the reprex below.

## packages
using Random, Distributions, LinearAlgebra

## set seed
Random.seed!(02192024);

# generate the distribution for X
μ = zeros(2);
Σ = [1 0; 0 1];
d = MvNormal(μ, Σ);
X = rand(d, 1000, 2); # one use of rand 

# generate the distribution for Z 
μ = zeros(3);
Σ = [1 0 0; 0 1 0; 0 0 1];
zd = MvNormal(μ, Σ);
Z = rand(zd, 1000, 3); # another use of rand

# generate the distribution for Y
Y = randn(1000, 1);

# define the projection matrix
Pz = Z * inv(Z'*Z) * Z';

# define X̂ and Ŷ
X̂ = Pz * X; # this is the line with the error
Ŷ = Pz * Y; # this line does NOT throw an error

I have looked up the error in question, but none of the results have been applicable to my particular issue. Thank you!


Solution

  • There is no need to specify for rand the dimension 2 or 3, since it is embedded in the distribution d or zd, just use rand(d,1000) and rand(zd, 1000).