1. A <- rbind(c(3,4),c(1,-1),c(4,3)) y <- c(18,-1,17) MASS::ginv(A) %*% y 2. library(rectools) hv <- getHouseVoting() hv <- hv[,-17] library(softImpute) hv <- as.matrix(hv) hvic <- as(hv,'Incomplete') aEst <- softImpute(hvic,5) si <- softImpute(hvic,5) # could use complete() instead: aEst <- si$u %*% diag(si$d) %*% t(si$v) aEst[3,1] # 0.35 3. library(MASS) als <- function(m,r,nmf=FALSE, w0=matrix(runif(nrow(m)*r),nrow=nrow(m)), eps=0.01*max(abs(m)),maxIters=100) { w <- w0 h <- matrix(rep(0,r*(ncol(m))),nrow=r) for (iter in 1:maxIters) { oldmest <- w %*% h gw <- ginv(w) for (j in 1:ncol(m)) { h[,j] <- gw %*% m[,j] if (nmf) h[,j] <- pmin(h[,j],0) # not min*( } gh <- ginv(t(h)) for (i in 1:nrow(m)) { ## w[i,] <- t(ginv(t(h)) %*% m[i,]) w[i,] <- t(gh %*% m[i,]) if (nmf) w[i,] <- pmin(w[i,],0) # not min*( } if (frob(w %*% h - oldmest) < eps) break if (iter == maxIters) warning('did not converge') } list(w=w,h=h,prd=w %*% h) } frob <- function(mat) { sqrt(sum(mat^2)) }