矢量范数/矩阵乘法

时间:2017-10-20 08:43:55

标签: r matrix vectorization

我有一个由矩阵if (_bImageFileOpen == false) { byte[] m_byte = new byte[4]; var openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); openFileDialog1.Filter = "Mnist Image file (*.idx3-ubyte)|*.idx3-ubyte"; openFileDialog1.Title = "Open Minist Image File"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { _MnistImageFileName = openFileDialog1.FileName; try { load_ImageFile_stream = new System.IO.BinaryReader(openFileDialog1.OpenFile()); //Magic number load_ImageFile_stream.Read(m_byte, 0, 4); Array.Reverse(m_byte, 0, 4); _ImageFileBegin.nMagic = BitConverter.ToInt32(m_byte, 0); //number of images load_ImageFile_stream.Read(m_byte, 0, 4); //High-Endian format to Low-Endian format Array.Reverse(m_byte, 0, 4); _ImageFileBegin.nItems = BitConverter.ToInt32(m_byte, 0); _nItems = (uint)_ImageFileBegin.nItems; //number of rows load_ImageFile_stream.Read(m_byte, 0, 4); Array.Reverse(m_byte, 0, 4); _ImageFileBegin.nRows = BitConverter.ToInt32(m_byte, 0); //number of columns load_ImageFile_stream.Read(m_byte, 0, 4); Array.Reverse(m_byte, 0, 4); _ImageFileBegin.nCols = BitConverter.ToInt32(m_byte, 0); _bImageFileOpen = true; return true; } catch { _bImageFileOpen = false; return false; } } return false; } return true;

描述的规范
sigma

计算向量计算的范数

sigma <- matrix(c(1,0.5,0,0.5,1,0,0,0,1),3,3))

适用于矢量,例如t(x) %*% sigma %*% x

但是我想同时计算许多向量的范数,就是我有

x = 1:3

(当然填写了不同的条目)。

有没有办法同时计算每个向量的范数? 即

之类的东西
x <- t(matrix(rep(1:3, 10),3,10))

3 个答案:

答案 0 :(得分:3)

你可以这样做:

sigma <- matrix(c(1,0.5,0,0.5,1,0,0,0,1),3,3)
x <- t(matrix(rep(1:3, 10),3,10))

mynorm <- function(x, sig) t(x) %*% sig %*% x
apply(x, 1, mynorm, sig=sigma)

以下是tcrossprod()的变体:

mynorm <- function(x, sig) tcrossprod(x, sig) %*% x
apply(x, 1, mynorm, sig=sigma)

以下是基准测试(包括来自compute only diagonals of matrix multiplication in R的解决方案的变体,感谢@Benjamin的链接):

mynorm1 <- function(x, sig) t(x) %*% sig %*% x
mynorm2 <- function(x, sig) tcrossprod(x, sig) %*% x

microbenchmark(n1=apply(x, 1, mynorm1, sig=sigma), 
               n2=apply(x, 1, mynorm2, sig=sigma), 
               n3 = colSums(t(x) * (sigma %*% t(x))),
               n4 = rowSums(x * t(sigma %*% t(x))),
               n5 = rowSums(x * (x %*% t(sigma) )),
               n6 = rowSums(x * tcrossprod(x, sigma)),
               Eugen1 = diag(x %*% sigma %*% t(x)),
               Eugen2 = diag(x %*% tcrossprod(sigma, x)),
               unit="relative")

答案 1 :(得分:2)

您如何看待这种简单的矩阵乘法:

 diag(t(x) %*% sigma %*% x)

编辑:在矩阵乘法之后,你需要对角线(当然)。

然后它比应用

的解决方案更快

答案 2 :(得分:2)

这应该

> sigma <- matrix(c(1,0.5,0,0.5,1,0,0,0,1),3,3)
> x <- t(matrix(rep(1:30, 10),3,10))
> 
> # should give
> t(x[1, ]) %*% sigma %*% x[1, ]
     [,1]
[1,]   16
> t(x[2, ]) %*% sigma %*% x[2, ]
     [,1]
[1,]   97
> 
> # which you can get by
> rowSums((x %*% sigma) * x)
 [1]   16   97  250  475  772 1141 1582 2095 2680 3337