Picking out elements of an array and sorting them

7 次查看(过去 30 天)
I have an array which size is 41 x 4 and it consists of 25 x 2 matrices. ( See picture)
I want Matlab to create a new array of 41 x 1 , starting with cell {1,1} of the array, and take the element (1,2). Then I want it to continue making the new array columnwise, and the next element should be cell {1,2} of the array and again element (1,2)
An example may explain it better.
This is the new array I want.
  • {1,1} (1,2)
  • {1,2} (1,2)
  • {1,3} (1,2)
  • {1,4} (1,2)
  • {1,1} (2,2)
  • {1,2} (2,2)
  • {1,3} (2,2)
  • {1,4} (2,2)..........
And then do this for all rows in the array.
Thanks in advance for the help!

回答(1 个)

Arjun
Arjun 2024-8-5,12:02
Hi,
As per my understanding of the question, you have a cell array of dimension 41x1 where each element of the array is an array of size 25x2 and you want to manipulate the data as specified in the question. Since no data is provided, I will create some dummy data and walk you through the process using some dummy code.
%Dummy data creation for replicating the problem
originalArray = cell(41, 4);
%Using for loop to index through the 2-d cell array and fill random data entries
for i = 1:41
for j = 1:4
originalArray{i, j} = randi(10, 25, 2); % Example 25x2 matrices with random integers
end
end
%Create placeholder for the extracted data
newArray = cell(41,1);
%Index variable to index into the newArray while filling
index = 1;
%Run a 3-nested loop to go row rise and then scan all the columns of that row 25 times
for row = 1:41
%Loop through each row of the 25x2 matrices and pick relevant data
tempArr = cell(100, 1);
tempIndex = 1;
for k = 1:25
% Loop through each column of the original array
for col = 1:4
% Extract the 25x2 matrix from the current cell
tempArr{tempIndex} = originalArray{row,col}(k,2);
tempIndex = tempIndex + 1;
end
end
newArray{index} = tempArr;
index = index+1;
end
Finally, the newArray contain the desired data.
This code is a general flow you can use it to apply to your application by plugging your data and renaming the variables wherever necessary.
In this question the use of for loops and usage of cell array are two key things, I am attaching the documentation so that you can take a deeper look into those.
I hope this will help!

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by