How to access an cell array using an cell array of indices

1 回表示 (過去 30 日間)
shelley
shelley 2017 年 4 月 28 日
回答済み: shelley 2017 年 5 月 1 日
Hello All, Suppose we have cell arrays as A={[1 2 3],[4 5 6 7 8],[9 10 11 12]} B={[1:2],[2:4],[1:3]} How can I access A using B as indices, namely, extracting the first cell of A, A{1} using the index number from B{1}, etc. Therefore the output will be {[1 2],[5 6 7],[9 10 11]}
I greatly appreciate your input!!

採用された回答

Stephen23
Stephen23 2017 年 4 月 29 日
Using cellfun (not faster, just more compact):
>> A = {[1,2,3],[4,5,6,7,8],[9,10,11,12]};
>> B = {1:2,2:4,1:3};
>> C = cellfun(@(a,b)a(b),A,B,'uni',0);
>> C{:}
ans =
1 2
ans =
5 6 7
ans =
9 10 11

その他の回答 (1 件)

shelley
shelley 2017 年 5 月 1 日
Thank you very much, John, Stephen! It's good to know cellfun is actually slower than or on par with for loop.

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by