How to easily separate and index a 3D matrix into individual 2D matrices?

86 views (last 30 days)
Hi all, I hope you can help me with my problem. We collected our CCD camera spectra - it's 120 spectra all in a single 3D matrix.The matrix dimension is 255x1024x120. Each odd scan is a reference and each even scan is a sample. Is there a convenient way to write a for loop or some other mechanism that will allow me to automatically separate this single 3D matrix into 60 reference matrices and 60 sample matrices each with the corresponding name? For example, if we take the first of the 120 scans, can we name it Reference_1? Then the second of the 120 scans would be Sample_1 and so on? I am not skilled with MatLab but I am trying to get better. I will appreciate any and all help! Thank you!

Accepted Answer

Matt J
Matt J on 15 Feb 2016
Edited: Matt J on 15 Feb 2016
Making 120 different matrix variables is not the way to go. If you do that, you lose all ability to loop over the matrices when processing them later.
If I call your 255x1024x120 array "Scans", then to un-interleave them, you can do,
The sensible/easy way to index them is now to keep them as 3D arrays and do things like Samples(:,:,i) and Reference(:,:,i). Depending on the manipulations you plan to do, it might make sense to split them up further into cell arrays,
and now you can index whole 2D matrices as Reference{i} and Samples{i}. The latter is probably the closest to the indexing syntax you were originally looking for, except of course that it still allows you to index them in a loop.
Stephen23 on 16 Feb 2016
Edited: Stephen23 on 16 Feb 2016
The easiest way is to not separate them into cell arrays, but to keep them in one numeric array, then you can simply call mean with its optional dim input:
refs_all = Scans(:,:,1:2:end);
refs_avg = mean(refs_all,3);
Note that this is good approach to writing code: keep your data in the simplest arrays possible, as this makes working with the data much easier. In this case all of your data is in a numeric array, so converting this to lots of separate numeric matrices inside of a cell array just makes your life more complicated. Only use more complicated structures if you really have to.

Sign in to comment.

More Answers (0)


Find more on Resizing and Reshaping Matrices in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!