converting SPARSE in matlab to r code.

Hi, i've been trying to convert some code from matlab into R, but am stumbling with mirroring the 'sparse' function from matlab into r. I've used sparseMatrix in r, but what i'm entering doesnt provide the same output. Below is the matlab code:

x_part = sparse(x == x_unique (1:end-1)');
y_part = sparse(y == y_unique (1:end-1)');

X = [sparse(true(n,1)),x_part,y_part];
Y = sparse(score(:));

coeffs = (X'*X)\(X'*Y);

Yhat = full(X*coeffs);

In r, I've tried:

x_part <- Matrix(t(x == x_unique[1:length(x_unique)-1]), sparse = T)
y_part <- Matrix(t(y == y_unique[1:length(y_unique)-1]), sparse = T)

X <- Matrix(matrix(1,n),x_part, y_part, sparse = T);
Y <- Matrix(score, sparse = T);
coeffs <- (t(X)*X) / (t(X)*Y)

Yhat <- full(X*coeffs)

...but it doesn't work.

Any thoughts on how to solve this within R, would be greatly appreciated.

Thanks in advance.

One clear and big difference is that in MATLAB, you are using the matrix product A*B, not the element-wise product A .* B, whereas in R A*B is the element-wise product, for the matrix product you need A %*% B.

Apart from that I have trouble understanding the code, it would help to provide a reproducible example, with some example data for x_unique, y_unique, end, and what the results are with your MATLAB code (so we can compare and see where the mismatches appear).

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.