The mat file is a 156*192*25 3D matrix. The data are a series of n=25 images in a mat file. How could I convert this 3D matrix into 25 2D matrix and display them independently? Thanks~
-
1you have already 25 2D matrices! you can call the n-th one using `varname(:,:,n)` ... casting to a cell array etc is just useless! – bla Feb 29 '16 at 19:38
-
If one of the answers has solved your question please consider [accepting it](http://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates that you've found a solution and this is no longer an open question. If your question is not answered, please explain what’s missing. – Daniel Mar 05 '16 at 00:04
2 Answers
I recommend not to split your stack of images, instead simply use I(:,:,3)
if you for example need the third image.
To display the images you can use:
montage(permute(I,[1,2,4,3]))
To display all images together. The permute is required because montage
expects a 156*192*1*25
for stacked grey scale images, the third dimension is reserved for colour channels. Alternatively to display an individual image use:
imshow(I(:,:,3));
To save each image to an individual mat file use:
for ix=1:size(I,3)
M=matfile(sprintf('image%03d',ix),'writable',true);
M.image=I(:,:,ix);
end

- 36,610
- 3
- 36
- 69
-
Thanks a lot~I could use I(:,:,t) to get the current x-y 2D data~ Furthermore, I want to save those 2D data in different independent mat files during the for loop(for different stack). So could you give some suggestion about how to save the current 2D data in a mat file during the for loop? – Echo0831 Feb 29 '16 at 20:20
-
I updated my answer, but before using it do you really need to split your dataset? Using `matfile` you could also keep all data in one file and load only the relevant parts. – Daniel Feb 29 '16 at 20:35
Using the mat2cell
command, you could convert the 3D value matrix to a array of 25
cells, where each cell holds a 156x192
2D value matrix:
M = rand(156,192,25); %// simulate your 3D data matrix
Mcell = mat2cell(M,156,192,ones(1,25));
Alternatively, using arrayfun
command:
Mcell = arrayfun(@(x) M(:,:,x), 1:25, 'UniformOutput', false)
You can now access the 25
images one by one as:
imageNum = 5; %// example: access image num. 5
image = Mcell{imageNum}; %// image: 156x192 value matrix
One benefit of keeping the images in a cell array is that you can easily apply e.g. the same filter to all images, making use of the cellfun
command, e.g.:
h = fspecial('motion', 50, 45);
McellFiltered = cellfun(@(x) imfilter(x, h), Mcell, ...
'UniformOutput', false);

- 70,367
- 12
- 127
- 192