replacing loop with cell of index values

2 ビュー (過去 30 日間)
Catherine
Catherine 2021 年 1 月 16 日
コメント済み: Catherine 2021 年 1 月 16 日
I don't know how to explain with words what I'm trying to do, so here is an example
%I have an array of values
s = [1:100];
% and I have a cell array of different index values
c{1} = 1;
c{2} = 1:5;
c{3} = 2:2:10;
% I would like a cell array t, where
t{1} = s(c{1});
t{2} = s(c{2});
% etc.
% I can do this with a loop, but I'm wondering if there is a way to do this without a loop as my set of indices are large.

採用された回答

Stephen23
Stephen23 2021 年 1 月 16 日
編集済み: Stephen23 2021 年 1 月 16 日
s = 1:100;
c{1} = 1;
c{2} = 1:5;
c{3} = 2:2:10;
out = cellfun(@(x)s(x),c,'uni',0);
out{:}
ans = 1
ans = 1×5
1 2 3 4 5
ans = 1×5
2 4 6 8 10
A well-written (i.e. correctly preallocated, etc.) loop will be faster.
  1 件のコメント
Catherine
Catherine 2021 年 1 月 16 日
Thank you. Good to know that the loop might be faster.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by