user001
user001

Reputation: 1848

applying function to each column of a matrix within a matlab cell array

Applying a function to each matrix within a cell array in MATLAB can be accomplished using the cellfun function. For instance, to determine the median of each matrix within a cell array, the following commands can be issued:

temp={[1;2;3;4;5] [6;7;8;9;10]}
cellfun(@median,temp)
ans =
    3     8

How can a similar operation be applied to the individual columns of the matrices within each cell of a cell array (for instance, the first column of the matrix within each cell)? For the following cell array, the desired output of applying the median function to the first column of the matrix in each cell is 3,9.

temp={[1 2;3 4;5 6] [7 8;9 10;11 12]}

How can the operation providing such an output be written? Lastly, how can this operation be performed such that the output from the Nth column of the matrix within each cell is stored in the Nth column of an output matrix?. In the simplified example above, for instance, 3,9 (the medians of the first columns of the matrices) would be stored in the first column of the output matrix; likewise, 4,10 (the medians of the second columns of the matrices) would be stored in the second column of the output matrix. The cell array (input) and desired median array (output) are shown below for convenience:

        cell-1  cell-2
input =  1  2    7  8
         3  4    9 10
         5  6   11 12

output = 3  4
         9 10

Thank you.

Upvotes: 0

Views: 2363

Answers (2)

cyang
cyang

Reputation: 5694

You're almost there, just need to rearrange the resulting elements.

temp = {[1 2; 3 4; 5 6] [7 8; 9 10; 11 12] [1 2; 3 4; 5 6; 7 8; 9 10]}
cell2mat(cellfun(@(m) median(m)', temp, 'UniformOutput', false))'

The UniformOuptut option combines the outputs of cellfun into a single array. Normally median returns a row matrix containing the median for each column, but here each row matrix is transposed before being combined (horizontally) with the other outputs.

Upvotes: 3

David
David

Reputation: 8459

This code works for your small example---but I'm not sure how to automate the matrix construction without for loops. I'm sure someone (maybe you!) will know a better way!

temp={[1 2;3 4;5 6] [7 8;9 10;11 12]}
C=cellfun(@median,temp,'UniformOutput',false)
A=[C{1}(1) C{1}(2);C{2}(1) C{2}(2)]

edit: Yes! cyang knew a better way!

Upvotes: 2

Related Questions