Indexing of cell array using cellfun

조회 수: 22 (최근 30일)
Jason Schroder
Jason Schroder 2011년 10월 19일
I have a cell array (10x1) where each cell is a numeric array (Mx2) and a vector with key indicies.
%Example [Code formatting SCd]
C=cell(10,1)
C{1}=rand(4,2)*10
C{2}=rand(5,2)*10...C{10}=rand(3,2)*10
V=1:10
I want to extract from C{1} the first element in V(1) C{2} the 2nd element of V(2)....
my initial thought was something like this, which of course doesn't work but...
out=cellfun(@(x) x(v(x),:),C, 'uniformoutput',false)
any suggestions on how do do this outside of a loop?
Thank You!

답변 (3개)

Sean de Wolski
Sean de Wolski 2011년 10월 19일
C = mat2cell(rand(100,2),ones(1,10)*10,2);
V = randperm(10).';
out = cellfun(@(c,idx)c(idx,:),C,num2cell(V))
perhaps?

Jason Schroder
Jason Schroder 2011년 10월 19일
Thanks Sean, this is close, but I don't think I was very clear in my question.
What I really want is this C{x}(V(x),:)
you code is spitting out C{x}(v(1),2)
Thanks though!

Jason Schroder
Jason Schroder 2011년 10월 19일
Actually Sean it DOES work, I just had to add the 'uniformoutput', false and it works great thanks! It goes to show I don't really understand the use of anonymous functions
if I understand this correctly your function is the equivalent of C{c}(V(idx),:)?
Anyways, thanks a bunch for your help!
  댓글 수: 1
Sean de Wolski
Sean de Wolski 2011년 10월 19일
that's what it is now that I made the edit. Basically it takes two 10x1 cells and does the same thing to each row of cells:
so
C(1)then the V(1) or V(1,:) parts etc.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by