I was hoping I could get some help using the cellfun function in MATLAB.
Let's say I have cell that contains 5 10x2 matrices, i.e.
C = {[10x2], [10x2]...,[10x2]}
However, I want a new cell that takes the first 5 rows across both columns in each array, i.e. I want
D = {[5x2], [5x2]...,[5x2]}
Is there a way to do this in Matlab using cellfun
? I tried doing
D = cellfun(@(x) x(1:5),C,'UniformOutput',false)
But then this returned a cell that only contained the first 5 rows of only the first column in each array (and was also transposed) i.e., I got
D = {[1x5], [1x5]...,[1x5]}
Hopefully I explained this well.
Can anyone help? I think there's a simple way to do it but I'm new to cellfun
. It seems useful though. Maybe there's an even easier way I'm not seeing?
You were missing the definition of indices of the columns:
A = rand(10,2)
C = {A,A,A,A,A};
%// here ....|
D = cellfun(@(x) x(1:5,:), C,'UniformOutput',false)
In this case you want all columns, that's why you use :
. You could also use x(1:5,1:2)
- in your case it's equal to x(1:5,:)
.
C =
Columns 1 through 5
[10x2 double] [10x2 double] [10x2 double] [10x2 double] [10x2 double]
D =
Columns 1 through 5
[5x2 double] [5x2 double] [5x2 double] [5x2 double] [5x2 double]