I have saved multidimensional arrays in Matlab before (e.g. an array A that has size 100x100x100) using a .mat file and that worked out very nicely.
What is the best way to save such multidimensional arrays in C? The only way I can think of is to store it as a 2D array (e.g. convert a KxNxM array to a KNxM array) and be careful in remembering how it was saved.
What is also desired is to save it in a way that can be opened later in Matlab for post-processing/plotting.
C does 3D arrays just fine:
although for very large arrays such as in your example, you would want to allocate the arrays dynamically instead of declaring them as
autovariables such as above, since the space forautovariables (usually the stack, but not always) may be very limited.Assuming all your dimensions are known at compile time, you could do something like:
This will allocate a D0xD1xD2 array from the heap, and you can access it like any regular 3D array.
If your dimensions are not known until run time, but you’re working with a C99 compiler or a C2011 compiler that supports variable-length arrays, you can do something like this:
If your dimensions are not known until runtime and you’re working with a compiler that does not support variable-length arrays (C89 or earlier, or a C2011 compiler without VLA support), you’ll need to take a different approach.
If the memory needs to be allocated contiguously, then you’ll need to do something like the following:
Note that you have to map your
i,j, andkindices to a single index value.If the memory doesn’t need to be contiguous, you can do a piecemeal allocation like so:
and deallocate it as
This is not recommended practice, btw; even though it allows you to index
dataas though it were a 3D array, the tradeoff is more complicated code, especially ifmallocfails midway through the allocation loop (then you have to back out all the allocations you’ve made so far). It may also incur a performance penalty since the memory isn’t guaranteed to be well-localized.EDIT
As for saving this data in a file, it kind of depends on what you need to do.
The most portable is to save the data as formatted text, such as:
This writes the data out as a sequence of floating-point numbers, with a newline at the end of each row, and two newlines at the end of each “page”. Reading the data back in is essentially the reverse:
Note that both of these snippets assume that the array has a known, fixed size that does not change from run to run. If that is not the case, you will obviously have to store additional data in the file to determine how big the array needs to be. There’s also nothing resembling error handling.
I’m leaving a lot of stuff out, since I’m not sure what your goal is.