File Exchange

image thumbnail


version (2.44 KB) by Jeremy Manning
Slice a tensor (n-d matrix) along the d^th dimension.

1 Download

Updated 03 Mar 2012

View License

%SLICES return a cell array of slices of a tensor along the specied dimension
% This function is useful for slicing high-dimensional images (e.g. fMRI
% images) into lower-dimensional pieces. The output can then be either
% processed directly, or passed into cellfun or arrayfun for further
% processing.
% x = slices(m,[d])
% m: a tensor (i.e. multi-dimensional matrix) that you wish to slice
% d: the dimnsion along which you wish to make the slices. default:
% d = ndims(m).
% x: a 1 by size(m,d) cell array of slices of m. each element of the
% cell array is an (ndims(m) - 1)-dimensional tensor.
% %create a tensor to slice
% m = reshape(1:100,10,10);
% %slice along first dimension: returns rows of m
% s1 = slices(m,1);
% %slice along second dimension: returns columns of m
% s2 = slices(m,2);
% %slice along third (or greater) dimension: returns m as a cell array
% s3 = slices(m,3);

Cite As

Jeremy Manning (2020). slices (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (2)

Stephen Cobeldick

Two stars for working as documented. Two stars for being very slow, pointlessly complicated, for replicating inbuilt functionality, and for using EVAL.

This submission uses thirty lines of code to basically replicate the inbuilt NUM2CELL and/or MAT2CELL: it builds character arrays that are used as indices and then evaluates them. It is not clear why this is required, as the three examples could be simply be replaced by simpler and faster NUM2CELL, and avoid the whole bother:

num2cell(m,2) % slices(m,1)

num2cell(m,1) % slices(m,2)

num2cell(m,1:2) % slices(m,3)

In fact the whole function could be entirely replaced with this one-line function:

function out = slices2(inp,d)
out = num2cell(inp,setdiff(1:ndims(inp),d));

which when tested on the sample data is more than ten times faster than this submission (1e4 iterations):

Elapsed time is 5.61956 seconds. % this submission
Elapsed time is 0.466047 seconds. % one-line function

Hardcoding the dimension would make the one-line solution faster still.

Summary: slow replication of inbuilt functions. Unclear why this is better than using NUM2CELL.



This is almost what I need. I see you implement the usage of a string as indexes. How did you manage to get MatLab to accept the colons? With my implementation it gives an error:

MATLAB Release Compatibility
Created with R2010a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired by: join

Inspired: 2d and 3d brain plots

Community Treasure Hunt

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

Start Hunting!