default output on screen of array of order > 2

4 views (last 30 days)
Hello
in what follow , the values "5" in the array are irrelevant
consider this command:
A = repmat(5,[2 2 2 2])
A(:,:,1,1) =
5 5
5 5
A(:,:,2,1) =
5 5
5 5
A(:,:,1,2) =
5 5
5 5
A(:,:,2,2) =
5 5
5 5
why , by deafult , Matlab visualizes as a second 2x2 sub-array the sub-array A(:,:,2,1)
and not the sub-array A(:,:,1,2) ?
cioe' as in the following (i manually modified the output) :
A(:,:,1,1) =
5 5
5 5
A(:,:,1,2) =
5 5
5 5
A(:,:,2,1) =
5 5
5 5
A(:,:,2,2) =
5 5
5 5
because seem more natural follow the sequence 1,1 1,2 2,1 2,2
I would really appreciate knowing why this sequence in the output was chosen.
Thankyou very much !
MA

Accepted Answer

Stephen23
Stephen23 on 14 Sep 2025
Edited: Stephen23 on 14 Sep 2025
"I would really appreciate knowing why this sequence in the output was chosen."
Because the displayed output exactly follows the order of data in memory. Your example "natural" sequence shows dimension 4 iterating the fastest followed by dimension 3, but in MATLAB dimension 1 iterates the fastest, followed by dimension 2, followed by dimension 3, followed by dimension 4, etc.
Thus the displayed matrices are displayed exactly in the order of blocks of data in memory. In contrast your "natural" sequence would require a very unnatural jumping about in memory to select non-sequential blocks of data, which could be fairly inefficient for large data arrays and quite unnatural for MATLAB's memory layout.
The same also applies to higher dimension data:
format compact
ones(1,1,2,2,2)
ans =
ans(:,:,1,1,1) = 1 ans(:,:,2,1,1) = 1 ans(:,:,1,2,1) = 1 ans(:,:,2,2,1) = 1 ans(:,:,1,1,2) = 1 ans(:,:,2,1,2) = 1 ans(:,:,1,2,2) = 1 ans(:,:,2,2,2) = 1
Note how the dimensions increment exactly in the order used by MATLAB for storing data in memory. Would you redefine it as iterating from the highest dimension first, regardless of how many dimensions? in which case, you are asking MATLAB to completely change its memory model, which is very unlikely to happen.
It seems that you expect the data to be row-major, but MATLAB stores data in column-major order:
  1 Comment
Val
Val on 14 Sep 2025
"It seems that you expect the data to be row-major, but MATLAB stores data in column-major order"
Thankyou Mr Stephen23 for the quick response , regards Valerio 🤝

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Products


Release

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!