I have a cell array A
of size 10x10
(say). Each cell in turn contains a 5x20
matrix. I want to select (i,j)
element from each cell, where (i,j)
are indices within a loop. I can run 4 for
loops and easily get the answer. It may even be faster as it has been discussed many times that loops could be faster than cellfun, structfun etc.
Still, is there any solution using cellfun
which I can use in a loop over (i,j)
and extract (i,j)
element in each cell? I tried writing a function which will act as handle to cellfun
but I couldn't access two-leves down i.e. A{eachCellRow,eachCellCol}(i,j)
.
Example:
If A={[1 2;5 6], [3 4; 6 7]; [3 4; 6 7], [9 8; 5 6]};
Then for i=1, j=1 and i=2, j=1
output should be:
B=[1 3; 3 9] and B=[5 6; 6 5]
If memory is not an issue, you can concat all matrices along a third dim; and then indexing is very easy:
The easy to use
cellfun
one-liner would be:gives:
Advantage over Divakar's Solution: it works also for inconsistent matrix sizes in
A
.And if you want to avoid also the outer loop, another fancy two-liner:
gives:
CELL2MAT gets all the data from a cell array that consists of numeric data only, into a numeric array. So, that helped us here. For your original problem, try this -