1

Can anyone help me on how to compute the Hii matrix

definition of Hii matrix

It is supposed to get a single values. However, in my code, it is appeared as 2x2 matrix. This is my code in Matlab:

faithfuldat = xlsread('faithful.csv');
save faithful.mat faithfuldat       % command form

[N,dim]=size(faithfuldat);
fData = faithfuldat;

X_ones =[ones(length(fData(:,1)),1) fData(:,1)];
hii = zeros(N);
for i = 1:N
    hii(i)=X_ones(i,:)'.*(X_ones'*X_ones).*X_ones(i,:)
end

If the code without using csv file in Matlab:

a = [1 20;1 30;1 40]

for i = 1:length(a)
    disp(a(i,:)'.*(a'*a).*a(i,:))
end

The code in R is works well:

n <- 50
k <- 2
b0 <- 2
b1 <- 3
x0 <- rep(1,50)
x1 <- rnorm(50)
e <- rnorm(50)
y <- b0 + b1*x1 + e

design.data <- matrix(c(x0,x1), ncol=2, byrow=F)

hii <- numeric()
for(j in 1:n){
  hii[j] <- t(design.data[j,]) %*% solve(t(design.data)%*%design.data) %*% matrix(design.data[j,])
}

Result:

[1] 0.03400676 0.05641070 0.04553599 0.05094598 0.02047051 0.08695448 0.10619427 0.02375806 0.02633310 0.02397181 0.02502073 0.02974964 0.02450914 0.02973598 0.02074476 0.02040370
[17] 0.02659910 0.06028877 0.02028375 0.02121156 0.02727598 0.03565958 0.07047492 0.03275287 0.02680609 0.05062417 0.06499097 0.02712547 0.02000748 0.06958282 0.02309955 0.02000024
[33] 0.02278708 0.02289988 0.05388652 0.02394204 0.03543398 0.09602045 0.02398702 0.02824829 0.03135704 0.06346209 0.02002556 0.10706917 0.05999023 0.02174539 0.04032562 0.05597862
[49] 0.03750268 0.03380938

Can anyone advice me on how to improve my code in Matlab so that i can get the result as yielded in R code.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
amjay
  • 11
  • 6

1 Answers1

0

With reference to your code

a = [1 20;1 30;1 40]
for i = 1:length(a)
       disp(a(i,:)'.*(a'*a).*a(i,:))
end

there are several issues:

  • Matrix product in Matlab is *, not .*.
  • a(i,:) is a row vector, not a column vector. So you need to move the transpose.
  • For transpose use .', not '. The operator ' is complex-conjugate transpose.
  • It's better not to use i as variable name.

So, change the thid line to the following (and additionally consider renaming i):

disp(a(i,:)*(a.'*a)*a(i,:).')
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147