0

i want to find "if matrix b is nonsingular matrix, find inverse of b else if then find generalized inverse of b"

so i made this statement . but it didn't work.

a<-c(1:9)
a
b<-matrix(a,3,3)
b
library(MASS)
ifelse(ncol(b)==nrow(b),(ifelse(det(b)==0,ginv(b),solve(b)),ginv(b))

then i modified the statement like this

a<-c(1:9)
a
b<-matrix(a,3,3)
b
library(MASS)
d<-ifelse(det(b)==0,ginv(b),solve(b))
e<-ginv(b)
ifelse(ncol(b)==nrow(b),d,e)

but the answer is just row=1 col=1 value of the generalize invers of b.

Please help me....

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
Insung Kang
  • 47
  • 1
  • 7
  • For debugging (given that the first problem was a lost `(` ), always a good idea to prove out the first `ifelse` and then insert the subordinate one. – Carl Witthoft May 12 '13 at 18:07

2 Answers2

0

You have a stray (

ifelse(ncol(b)==nrow(b),ifelse(det(b)==0,ginv(b),solve(b)),ginv(b))
## [1] -0.6388889

Note that you don't need ifelse for this. ncol(b)==nrow(b) does not return a vector, nor does det(b)==0.

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
0

To answer your question, return value using simple if and else statements. Replace

d <- ifelse(det(b)==0,ginv(b),solve(b))
e <- ginv(b)
ifelse(ncol(b)==nrow(b),d,e)

by this:

d <- if(det(b)==0) ginv(b) else solve(b)
e <- ginv(b)
if(ncol(b)==nrow(b)) d else e

##            [,1]          [,2]       [,3]
## [1,] -0.6388889 -5.555556e-02  0.5277778
## [2,] -0.1666667 -9.234353e-17  0.1666667
## [3,]  0.3055556  5.555556e-02 -0.1944444
Nishanth
  • 6,932
  • 5
  • 26
  • 38