While studying arrays a question came to my mind. If only 1D and 2D arrays can be used, then why multi-dimensional arrays exist? Is there any use of multi-dimensional arrays?
closed as unclear what you're asking by David Richerby, Evil, Juho, hengxin, Gilles Dec 19 '16 at 10:58
Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.
One could just as easily ask "what are the uses of multidimensional spaces?" After all, with space-filling curves, all we really need is one dimension.
But a single dimension, even if it's sufficient, does not always yield useful models. For example, a 2-dimensional euclidean line would be non-continuous when mapped to a space-filling curve.
It's the same with multi-dimensional arrays -- they're used not because they're inherently necessary, but because they're a useful model.
For example, let's take a look at how one might model a movie.
- A movie is nothing more than a time-varying sequence of images -- i.e., an array of images.
- Each image is a two-dimensional array, with each element of the array representing a color.
- A color has three components:
So a movie can be modeled as a multidimensional array.
An array is nothing else than a named association from integers (in a range) to another data item, usually optimized to have a cost O(1) for the retrieve data operation. Using your words "only 1D arrays exist".
The usual expressions:
a(1), or even the unusual
a.1 are sugar of
get(a,1) in some not oo languages,
get a 1 in others, etc).
If the data item returned is itself an array, we could talk about a bidimensional array. Thus, bidimensional expressions
a.get(4).get(2). Three dimensional ones are
a.get(2).get(4).get(7), and so on.
About the example you request, assume you have a big library, with several floors, rooms in each floor, bookstore in each floor, shelfs in each bookstore and slots in each shelf. All they are numbered (floor 1, room 3, bookstore 4, shelf 1, slot 7). You can retrieve data for one specific book as:
mylibrary.get(1).get(3).get(4).get(1).get(7), that some languages will write as
mylibrary, ... .
A person can easily reason about n-dimensional vectors in code. A 2-D vector is simply a vector of vectors. A 3-D vector is a vector of vector of vectors and so on and so on. You can construct a 1-D vector to behave like an N-dimensional vector however, but this is typically more difficult to reason about.
General code for a 3-D vector:
for i to N for j to N for k to N dosomething(vec[i,j, k])
You can have more for loops and this will traverse every element in your N-dimensional vector