MATLAB Answers


How to sort coordinates into a multi dimensional array?

Asked by Abinav Shankar on 30 Sep 2019
Latest activity Answered by Raunak Gupta on 4 Oct 2019
I have three points P1(x1,y1), P2(x2,y2) and P3(x3,y3) and there are 42 values of these points. Through calculation I have individual arrays of x1, x2, y1, y2, x3 and y3. How do I sort them into a multi dimensional array. I want it to be in the form of P = [(x1,y1),(x2,y2),(x3,y3)] and 42 elements in the other dimensions making it a 4D array i.e. 1 Row: 3 Columns: 2 Elements in each column: 42 Layers.


Can you elaborate more easily (with examples)? Please note that numerical or math is much easier to understand than long text.
I have three set of points, P1 with coordinates (x1,y1), P2 with (x2,y2) and P3 with (x3,y3). These three points form a line. I have 42 set of these points i.e. P11,P12, P13,..P142. Similarly 42 set exists for other two points P2 and P3.
From other calculations I have found individual values of x1, x2, y1, y2, x3 and y3. These are in the form of individual row vectors. X1 = [x11, x12, x13,...x142] and Y1 = [y11,y12,y13,...y142]. Similarly, I have row vectors X2, Y2, X3 and Y3 with 42 elements.
I want to sort them in the form of a multi dimensional array P = [(x1,y1),(x2,y2),(x3,y3)]. P has 1 row, 3 columns, 2 elements in each column and 42 pages. So P would be a 1:3:2:42 array. How do I create such an array from my indivdual vectors.

Sign in to comment.

1 Answer

Answer by Raunak Gupta on 4 Oct 2019

For creating a 4D array you may use array indexing however for using sort, the dimension on which sorting is needed may be clearly visualized as the structure of array changes after choosing a particular dimension. For creating 4D array so may follow the below example.
X1 = randi(12,1,42); % These are individual row vectors
Y1 = randi(12,1,42);
X2 = randi(12,1,42);
Y2 = randi(12,1,42);
X3 = randi(12,1,42);
Y3 = randi(12,1,42);
Coordinates(1,:,:) = [X1;Y1]; %P1
Coordinates(2,:,:) = [X2;Y2]; %P2
Coordinates(3,:,:) = [X3;Y3]; %P3
final(1,:,:,:) = Coordinates;
% Above final Matrices will be of size 1 x 3 x 2 x 42
If it is required to sort along 2nd dimension with shows P1,P2,P3 then the sort function will compare the values P1,P2,P3 for all corresponding 2 X 42 matrix and will arrange them as required in ascending and descending order. So, the pairing of previous (x11,y11) , (x12,y12) etc. will change. That is why it is recommended to visualize how the sorting is required or what should be the end result.


Sign in to comment.