Matlab to C porting
I'm working onto several routines that i've to port from Matlab to Ansi-C. Since i'm not a Matlab veteran i try to ask to you about some cryptic rows.
1)
%Matlab
[X,Y] = meshgrid(-k:k,-k:k);
Supposing that k == 3, the above line is supposed to make TWO Matrix (X and Y) With the following aspect:
[-3, -2, -1, 0, 1, 2, 3]
[-3, -2, -1, 0, 1, 2, 3]
[-3, -2, -1, 0, 1, 2, 3]
X= [-3, -2, -1, 0, 1, 2, 3]
[-3, -2, -1, 0, 1, 2, 3]
[-3, -2, -1, 0, 1, 2, 3]
[-3, -2, -1, 0, 1, 2, 3]
[-3, -3, -3, -3, -3, -3, -3]
[-2, -2, -2, -2, -2, -2, -2]
[-1, -1, -1, -1, -1, -1, -1]
Y= [ 0, 0, 0, 0, 0, 0, 0]
[ 1, 1, 1, 1, 1, 1, 1]
[ 2, 2, 2, 2, 2, 2, 2]
[ 3, 3, 3, 3, 3, 3, 3]
is this correct?
2) The following statement, i suppose that create a submatrix, is there any efficent way to convert it in regular C?
I = A(iMin:iMax,jMin:jMax,:); 开发者_运维知识库
Thanks for help!
1) Yes :-)
2) I guess you have to loop over the second and third index (lets call them j and k) of the array and copy each of the ranges of the form A(iMin:iMax,j,k) manually.
Regarding your second question, there is no shortcut if you don't want to use any other libraries. The operation is called array slicing so Google might help if you search for a C library that might offer something similar.
Also, if you don't mind writing it in C++ instead of C, you might take a look at http://arma.sourceforge.net/docs.html#syntax There are various other linear algebra libraries on C and C++ I'm sure, but armadillo seems to be closest to what MATLAB can offer.
1) Yes, but if you are writing your own code, there is no reason to waste all the space from the duplication. A X-Vector and Y-Vector as such:
int X[] = {-3, -2, -1, 0, 1, 2, 3};
int Y[] = {-3, -2, -1, 0, 1, 2, 3};
will allow you to access the same information but without the memory waste (which might be a big issue on an embedded system). Rather than access X(i,j)
and Y(i,j)
, you access X[i]
and Y[j]
.
2) Depending on how large your arrays are, there may be more efficient options than accessing element by element. Assuming you are storing your array in row-major order (i.e.
A_1,1 A_1,2 A_1,3 ... A_1,n
A_2,1 ...
is stored A_1,1 A_1,2 A_1,3 ... A_1,n A_2,1 ...
You can copy a slice by the following:
/* Initialization code omitted, let A be n x m */
/* Also assuming that [i/j][Max/Min] are zero indexed */
int i, diff_i, diff_j;
diff_i = iMax - iMin;
diff_j = jMax - jMin;
size_t stride = sizeof(YOUR DATA TYPE HERE) * (1 + diff_j);
/* I = A(iMin:iMax,jMin:jMax,:); */
for(i = 0; i <= diff_i; i++){
memcpy(&I[i*diff_j],&A[i*m + jMin],stride);
}
This will grab a row at a time rather than a single element at a time.
精彩评论