[R] loops for matrices

Rainer Schuermann rainer.schuermann at gmx.net
Wed Jun 12 11:24:52 CEST 2013


The comments on StackOverflow are fair, I believe...
Please dput() your matrices, so that your code becomes reproducible!


On Wednesday 12 June 2013 11:14:35 maggy yan wrote:
> I have to use a loop (while or for) to return the result of hadamard
> product. now it returns a matrix, but when I use is.matrix() to check, it
> returns FALSE, whats wrong?
> 
> Matrix.mul <- function(A, B)
> {
>     while(is.matrix(A) == FALSE | is.matrix(B) == FALSE )
>          {print("error")
>           break}
>     while(is.matrix(A) == T & is.matrix(B) == T)
>          {
>           n <- dim(A)[1]; m <- dim(A)[2];
>           p <- dim(B)[1]; q <- dim(B)[2];
>           while(m == p)
>                {
>                 C <- matrix(0, nrow = n , ncol = q)
>                 for(s in 1:n)
>                    {
>                     for(t in 1:q)
>                        {
>                         c <- array(0, dim = m )
>                         for(k in 1:m)
>                            {
>                             c[k] <- A[s,k] * B[k, t]
> 
>                             }
>                         C[s, t] <- sum(c)
>                        }
>                    }
>                 print(C)
>                 break
>                 }
>           while(m != p)
>                {
>                 print("error")
>                 break
>                 }
>           break
>           }
> }
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list