Accessing columns of array elements in a cell array without for loops

I have a K-element cell array C1. Each element is an Nx3 array of doubles. How can I get a new cell array whose elements are the first column of each array in C1 using only logical indexing? For example, if C1 is {M1 M2 M3}, where M1=[1 2 3; 4 5 6; 7 8 9]=M2=M3; then I want a new cell array C2 that is {N1 N2 N3} where N1=[1;4;7]=N2=N3.
*Edit: My mistake, the K matrices do not all have the same number of rows (but they do all have 3 columns). See my comment below.
I can do this with a for loop:
for j=1:length(C1)
mat=C1{j}(:,1);
C2{j}=mat;
end
How can I do it without a loop?

2 Comments

is = [true(3,1),false(3,2)]
cellfun( @(c) c(is), C1, 'uni',false)
outputs
is =
1 0 0
1 0 0
1 0 0
ans =
[3x1 double] [3x1 double] [3x1 double]
However, I used array indexing to create the logical index. I give up.
Sorry, I should have specified that the K matrices are not necessarily all the same size; they each have 3 columns but an arbitrary number of rows. So they are not all Nx3 matrices, but rather nx3 matrices where n is different for each C{k}. My apologies.

Sign in to comment.

 Accepted Answer

C2 = cellfun(@(x)x(:,1),C1,'UniformOutput',false);

5 Comments

This solution violates "using only logical indexing" :-)
Clever (+1 vote) but I wonder why, since the array sizes are all the same and not variable, he doesn't simply use a 2D double array instead of a cell array, which is always more complicated.
I agree with the above comments. :-)
I guess this is impossible using only logical indexing... disappointing. But this cellfun does the trick, thanks!
Did you see my solution below? It does it, at least for a known, fixed value of K. And you didn't explain why you are even using cells in the first place.

Sign in to comment.

More Answers (1)

Perhaps you want something like this:
% Setup:
% Define K random 3x3 matrices for the K M arrays.
% K = 3 in this example.
M1 = [1 2 3; 4 5 6; 7 8 9]
M2 = randi(9, 3, 3)
M3 = randi(9, 3, 3)
% Create C1 from the M's.
C1 = {M1 M2 M3}
% Solution:
% Use logical indexing to get Ns as the first column of the M's.
N1 = M1(logical([1, 0, 0, 1, 0, 0, 1, 0, 0]))'
N2 = M2(logical([1, 0, 0, 1, 0, 0, 1, 0, 0]))'
N3 = M3(logical([1, 0, 0, 1, 0, 0, 1, 0, 0]))'
% Create C2, a 1-by-3 cell array, that is the 3 column vectors
% (first columns of the M's) each in their own cell.
C2 = {N1 N2 N3}
celldisp(C2)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

Ted
on 19 Aug 2017

Edited:

on 19 Aug 2017

Community Treasure Hunt

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

Start Hunting!