-
Notifications
You must be signed in to change notification settings - Fork 36
/
matfile.c
390 lines (356 loc) · 8.81 KB
/
matfile.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/* matfile utility program
* Allows you to read and write MAT files from the command line.
* Useful for manipulating large data structures via a combination of
* unix and matlab commands.
* Run without arguments for a description of usage.
* The file test_matfile.mat is provided for you to play with.
*
* Thomas P Minka 3/25/99
* 1/29/00 added sparse matrices
*/
#include <stdio.h>
#include <ctype.h> /* for isspace() */
#include "mat.h"
#define Allocate(n,t) (t*)malloc((n)*sizeof(t))
#define Reallocate(p, n, t) ((p)=(t*)realloc((p),(n)*sizeof(t)))
void directory(MATFile *pmat)
{
int i;
#if 0
int ndir;
char **dir;
dir = matGetDir(pmat, &ndir);
if (dir == NULL) {
fprintf(stderr, "Error reading directory\n");
exit(1);
}
for (i=0; i < ndir; i++) {
printf("%s\n",dir[i]);
}
#else
const char *name;
printf("Name\t\t Size \t Bytes\tClass\n\n");
for (i=0;;i++) {
mxArray *pa = matGetNextVariableInfo(pmat, &name);
int ndims;
const int *dims;
int size;
if(pa == NULL) {
break;
}
printf("%-10s ", name);
ndims = mxGetNumberOfDimensions(pa);
dims = mxGetDimensions(pa);
for(i=0;i<ndims;i++) {
if(i == 0) printf("%10d", dims[i]);
else printf("x%d", dims[i]);
}
if(mxIsSparse(pa)) {
size = mxGetNzmax(pa)*(mxGetElementSize(pa) + sizeof(int));
size += (mxGetN(pa)+1)*sizeof(int);
}
else {
size = mxGetNumberOfElements(pa)*mxGetElementSize(pa);
}
printf("\t%10d", size);
printf("\t%s", mxGetClassName(pa));
if(mxIsFromGlobalWS(pa)) printf(" (global)");
printf("\n");
}
#endif
}
void extract(MATFile *pmat, char *var)
{
mxArray *pa = matGetArray(pmat, var);
int ndims;
if(pa == NULL) {
fprintf(stderr, "There is no variable named %s\n", var);
exit(1);
}
ndims = mxGetNumberOfDimensions(pa);
if(ndims > 2) {
fprintf(stderr, "Cannot handle more than two dimensions. Sorry.\n");
exit(1);
}
if(mxIsSparse(pa)) {
fprintf(stderr, "Cannot extract sparse matrices. Sorry.\n");
exit(1);
}
if(mxIsComplex(pa)) {
fprintf(stderr, "Cannot extract complex matrices. Sorry.\n");
exit(1);
}
if(mxIsDouble(pa)) {
int i, j;
const int *dims = mxGetDimensions(pa);
for(i=0;i<dims[0];i++) {
double *p = mxGetPr(pa) + i;
for(j=0;j<dims[1];j++) {
printf("%g ", *p);
p += dims[0];
}
printf("\n");
}
}
else {
fprintf(stderr, "Can only handle double-precision variables. Sorry.\n");
exit(1);
}
mxFree(pa);
}
/****************************************************************************/
typedef struct DoubleArray {
double *d;
int len, bufsize;
} DoubleArray;
DoubleArray *DoubleArray_Create(void)
{
DoubleArray *a = Allocate(1, struct DoubleArray);
a->bufsize = 32;
a->len = 0;
a->d = Allocate(a->bufsize, double);
return a;
}
void DoubleArray_Free(DoubleArray *a)
{
free(a->d);
free(a);
}
void DoubleArray_Set(DoubleArray *a, int index, double value)
{
if(index >= a->bufsize) {
do {
a->bufsize *= 2;
} while(index >= a->bufsize);
Reallocate(a->d, a->bufsize, double);
}
if(index >= a->len) a->len = index+1;
a->d[index] = value;
}
/****************************************************************************/
typedef struct IntArray {
int *d;
int len, bufsize;
} IntArray;
IntArray *IntArray_Create(void)
{
IntArray *a = Allocate(1, struct IntArray);
a->bufsize = 32;
a->len = 0;
a->d = Allocate(a->bufsize, int);
return a;
}
void IntArray_Free(IntArray *a)
{
free(a->d);
free(a);
}
void IntArray_Set(IntArray *a, int index, int value)
{
if(index >= a->bufsize) {
do {
a->bufsize *= 2;
} while(index >= a->bufsize);
Reallocate(a->d, a->bufsize, int);
}
if(index >= a->len) a->len = index+1;
a->d[index] = value;
}
/****************************************************************************/
typedef void ScanFunc(int r, int c, double d, void *info);
void scan(int *rows_return, int *cols_return, ScanFunc *f, void *info)
{
int rows, cols, i;
double d;
FILE *fp = stdin;
/* Use the first line to determine the number of columns */
for(i=0;;) {
int c = getc(fp);
if(c == '\n') break;
if(isspace(c)) continue;
ungetc(c, fp);
if(fscanf(fp, "%lg", &d) < 1) {
fprintf(stderr, "scan failed: expected a real number\n");
goto error;
}
f(0, i, d, info);
i++;
}
cols = i;
/* Read the rest of the lines */
for(rows=1;;rows++) {
int j;
for(j = 0; j < cols; j++) {
if(fscanf(fp, "%lg", &d) < 1) {
if(!feof(fp)) {
fprintf(stderr, "scan failed: expected a real number\n");
goto error;
}
else if(j > 0) {
fprintf(stderr, "scan failed: unexpected end of file\n");
goto error;
}
break;
}
f(rows, j, d, info);
}
if(feof(fp)) break;
}
*rows_return = rows;
*cols_return = cols;
error:
return;
}
void transpose(double *dest, double *src, int rows, int cols)
{
double *dest_save = dest;
int i,j;
for(i=0;i<rows;i++) {
dest = dest_save + i;
for(j=0;j<cols;j++) {
*dest = *src++;
dest += rows;
}
}
}
struct FullInfo {
DoubleArray *a;
int index;
};
void ScanFull(int r, int c, double d, struct FullInfo *info)
{
DoubleArray_Set(info->a, info->index++, d);
}
struct SparseInfo {
DoubleArray *data;
IntArray *ir, *jc;
int next_row;
int index;
};
void ScanSparse(int r, int c, double d, struct SparseInfo *info)
{
if(d == 0) return;
DoubleArray_Set(info->data, info->index, d);
IntArray_Set(info->ir, info->index, c);
/* start of new row? */
if(r >= info->next_row) {
/* fill in all rows up to r */
for(; info->next_row <= r; info->next_row++) {
IntArray_Set(info->jc, info->next_row, info->index);
}
}
info->index++;
}
void update(MATFile *pmat, char *var, int global, int sparse)
{
int rows, cols, status;
mxArray *pa;
if(sparse) {
int nzmax;
struct SparseInfo *info = Allocate(1, struct SparseInfo);
info->index = 0;
info->next_row = 0;
info->data = DoubleArray_Create();
info->ir = IntArray_Create();
info->jc = IntArray_Create();
scan(&rows, &cols, (ScanFunc*)ScanSparse, info);
/* fill out jc */
for(; info->next_row <= rows; info->next_row++) {
IntArray_Set(info->jc, info->next_row, info->index);
}
/* note rows and cols are swapped */
nzmax = info->index;
if(rows > nzmax) nzmax = rows;
pa = mxCreateSparse(cols, rows, nzmax, mxREAL);
memcpy(mxGetPr(pa), info->data->d, info->index*sizeof(double));
memcpy(mxGetIr(pa), info->ir->d, info->index*sizeof(int));
memcpy(mxGetJc(pa), info->jc->d, (rows+1)*sizeof(int));
DoubleArray_Free(info->data);
IntArray_Free(info->ir);
IntArray_Free(info->jc);
free(info);
}
else {
struct FullInfo *info = Allocate(1, struct FullInfo);
info->a = DoubleArray_Create();
info->index = 0;
scan(&rows, &cols, (ScanFunc*)ScanFull, info);
pa = mxCreateDoubleMatrix(rows, cols, mxREAL);
transpose(mxGetPr(pa), info->a->d, rows, cols);
DoubleArray_Free(info->a);
free(info);
}
mxSetName(pa, var);
if(global) status = matPutArrayAsGlobal(pmat, pa);
else status = matPutArray(pmat, pa);
if(status) {
fprintf(stderr, "matPutArray failed\n");
exit(1);
}
}
void delete(MATFile *pmat, char *var)
{
if(matDeleteArray(pmat, var)) {
fprintf(stderr, "matDeleteArray failed\n");
exit(1);
}
}
void printUsage(void)
{
fprintf(stderr, "matfile utility program by Thomas P Minka\n");
fprintf(stderr, "\nusage: matfile cmd file [var]\n\n");
fprintf(stderr, "cmd is one of\n");
fprintf(stderr, "\tt\tList the contents of file\n");
fprintf(stderr, "\tx\tExtract var and print on stdout\n");
fprintf(stderr, "\tu\tUpdate var from stdin\n");
fprintf(stderr, "\tug\tSame as u but make var global\n");
fprintf(stderr, "\tus\tSame as u but make var sparse (result will be transposed)\n");
fprintf(stderr, "\td\tDelete var\n");
exit(1);
}
int main(int argc, char *argv[])
{
MATFile *pmat;
char *cmd, *file;
if(argc < 3) {
printUsage();
}
cmd = argv[1];
file = argv[2];
if((cmd[0] == 'u') || (cmd[0] == 'd')) {
pmat = matOpen(file, "u");
if((pmat == NULL) && (cmd[0] == 'u')) {
pmat = matOpen(file, "w");
}
}
else {
pmat = matOpen(file, "r");
}
if(pmat == NULL) {
fprintf(stderr, "Cannot open file %s: ", file);
perror("");
exit(1);
}
switch(cmd[0]) {
case 't':
if(argc != 3) printUsage();
directory(pmat);
break;
case 'x':
if(argc != 4) printUsage();
extract(pmat, argv[3]);
break;
case 'u':
if(argc != 4) printUsage();
update(pmat, argv[3], cmd[1] == 'g', cmd[1] == 's');
break;
case 'd':
if(argc != 4) printUsage();
delete(pmat, argv[3]);
break;
default:
fprintf(stderr, "Unknown command `%s'\n", cmd);
}
matClose(pmat);
exit(0);
}