# Split 3D matrix into many 2D matrix and save them individually in matlab

2 views (last 30 days)
Ming on 12 Dec 2013
Answered: Abhijit Nayak on 1 Jun 2022
I have a 3D matlab matrix mamed "P3D", row*column*page=64*153*4096. I want to split it into 2D matrix according to the page. I want to get 2D matrix, row*colume=64*153 and the total number of these 2D matrix is 4096. Let's say they are "P2Di" , i=1 to 4096. Also I want to save the 2D matrix into the format of .csv and finally get 4096 .csv files. How could I do this in matlab? Thank you. I am a beginner with matlab.

Abhijit Nayak on 1 Jun 2022
So, we need a way to extract the 2D matrix along z-axis and then save them as .csv file.
I have given a code below for (3*4*2) 3D matrix. Make the changes of the size as per your requirements and proceed.
The following example code should give the desired result:
%P3D stores your desired 3D matrix of size 64*153*4096.
%Assign your available 3D matrix to P3D.
P3D = rand(3,4,2);
[x y z] = size(P3D)
for itr = 1:z
filename = "P2D"+itr+".csv";
new_matrix = P3D(:,:,itr);
writematrix(new_matrix, filename)
end
You will find the saved 4096 .csv files in the MATLAB folder in your pre-set pathway.
P.S: You can use ‘csvwrite’ function too instead of ‘writematrix’ function.
You can go through the link provided below to write individual 2D matrixes into the .csv files: