# 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.

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).