matlab sub2ind利用c语言重写
matlab sub2ind利用c语言重写
#include
#include
#include
#include
#include
typedef struct _sub2ind_res {
unsigned char val;
int id;
int rows;
int cols;
}sub2ind_res;
int sub2ind_uint8(unsigned char* ptr, int rows, int cols, int* x_id, int* y_id, int nums, sub2ind_res* res) {
assert(nums < cols && nums < rows);
if (res == NULL) {
res = (sub2ind_res*)malloc(nums*sizeof(sub2ind_res));
memset(res, 0, nums*sizeof(sub2ind_res));
}
for (int i = 0; i < nums; i++) {
int x = x_id[i];
int y = y_id[i];
int id = y * cols + x;
res[i].val = ptr[id];
res[i].id = id;
res[i].rows = y;
res[i].cols = x;
}
return nums;
}
int main(int argc, char** argv) {
srand((unsigned)time(NULL));
unsigned char randData[100] = { 0 };
for (int i = 0; i < 100; i++)
{
randData[i] = rand() % 100 + 1;
}
int rows = 10;
int cols = 10;
int x_id[] = { 1, 3, 6 };
int y_id[] = { 2, 5, 8 };
sub2ind_res res[3];
sub2ind_uint8(randData, rows, cols, x_id, y_id, 3, res);
for (int i = 0; i < 3; i++) {
printf("data(%d, %d) = %d, id = %d\n", res[i].cols, res[i].rows, res[i].val, res[i].id);
}
return 0;
}