Posts

Showing posts with the label Matlab

Converting Between Matrix Subscripts And Linear Indices (like Ind2sub/sub2ind In Matlab)

Answer : This is not something I've used before, but according to this handy dandy Matlab to R cheat sheet, you might try something like this, where m is the number of rows in the matrix, r and c are row and column numbers respectively, and ind the linear index: MATLAB: [r,c] = ind2sub(size(A), ind) R: r = ((ind-1) %% m) + 1 c = floor((ind-1) / m) + 1 MATLAB: ind = sub2ind(size(A), r, c) R: ind = (c-1)*m + r For higher dimension arrays, there is the arrayInd function. > abc <- array(dim=c(10,5,5)) > arrayInd(12,dim(abc)) dim1 dim2 dim3 [1,] 2 2 1 You mostly don't need those functions in R. In Matlab you need those because you can't do e.g. A(i, j) = x where i,j,x are three vectors of row and column indices and x contains the corresponding values. (see also this question) In R you can simply: A[ cbind(i, j) ] <- x

C Implementation Of Matlab Interp1 Function (linear Interpolation)

Answer : I've ported Luis's code to c++. It seems to be working but I haven't checked it a lot, so be aware and re-check your results. #include <vector> #include <cfloat> #include <math.h> vector< float > interp1( vector< float > &x, vector< float > &y, vector< float > &x_new ) { vector< float > y_new; y_new.reserve( x_new.size() ); std::vector< float > dx, dy, slope, intercept; dx.reserve( x.size() ); dy.reserve( x.size() ); slope.reserve( x.size() ); intercept.reserve( x.size() ); for( int i = 0; i < x.size(); ++i ){ if( i < x.size()-1 ) { dx.push_back( x[i+1] - x[i] ); dy.push_back( y[i+1] - y[i] ); slope.push_back( dy[i] / dx[i] ); intercept.push_back( y[i] - x[i] * slope[i] ); } else { dx.push_back( dx[i-1] ); dy.push_back( dy[i-1] ); slo...