niceman
niceman

Reputation: 2673

access cell array by two vector not pairwise

If I have a Cell array 2*2 where A{i,j} is a matrix, and I have two vectors v=1:2,c=1:2.

I want A(v,c) to return only A{1,1} and A{2,2} but matlab returns every combination of the two(aka also returns A{1,2} and A{2,1}).

Is there a way without using loops or cellfun ?

Upvotes: 0

Views: 66

Answers (1)

rayryeng
rayryeng

Reputation: 104503

What I suspect you are doing is something like this:

B = A(v, c);

When you specify vectors to index into A, it finds the intersection of coordinates and gives you those elements. As such, with your indexing you are basically returning all of the elements in A.

If you want just the top left and lower right elements, use sub2ind instead. You can grab the column-major indices of those locations in your cell array, then slice into your cell array with these indices:

ind = sub2ind(size(A), v, c);
B = A(ind);

Example

Let's create a sample 2 x 2 cell array:

A = cell(2,2);
A{1,1} = ones(2);
A{1,2} = 2*ones(2);
A{2,1} = 3*ones(2);
A{2,2} = 4*ones(2);

Row 1, column 1 is a 2 x 2 matrix of all 1s. Row 1, column 2 is a 2 x 2 matrix of 2s, row 2 column 1 is a 2 x 2 matrix of all 3s and the last entry is a 2 x 2 matrix of all 4s.

With v = 1:2; c=1:2;, running the above code gives us:

>> celldisp(B)

B{1} =

     1     1
     1     1

B{2} =

     4     4
     4     4

As you can see, we picked out the top left and bottom right entries exactly.

Minor Note

If it's seriously just a cell array of 2 x 2, and you only want to pick out the top left and lower right elements, you can just do:

B = A([1 4]);

sub2ind would equivalently return 1 and 4 as the column major indices for the top left and lower right elements. This avoids the sub2ind call and still achieves what you want.

Upvotes: 1

Related Questions