How to index a cell array of character vectors?

10 ビュー (過去 30 日間)
Ludovico Nati
Ludovico Nati 2022 年 2 月 28 日
編集済み: Voss 2022 年 3 月 1 日
Hello everyone,
I have problem in my code. Suppose I have 'c' which is a cell array of character vectors of dimension N by 1. I would like to index each element of 'c' with a given pair of 'si' (start index) and 'ei' (end index), which can be different for any element of 'c'. 'si' and 'ei' are both N by 1 numerical vector or cell array containg numerical elements.
I would like a function to use in cellfun like in this piece of code: newc = cellfun(@tbd,c,si,ei,'UniformOutput',false). 'newc' of course is a new cell array of character vectors , where the ith element would be like: newc{i} = x{i}(si{i}:ei{i});
I can create a function tbd (to be determined) by myself but I think that there are already more efficient and native way to do it.
Thanks for your help!

採用された回答

Voss
Voss 2022 年 3 月 1 日
編集済み: Voss 2022 年 3 月 1 日
% If si and ei are cell arrays containing scalar indices:
c = {'indexing'; 'a cell array'; 'of character'; 'vectors'};
si = {1; 3; 4; 5};
ei = {5; 6; 7; 6};
newc = cellfun(@(x,y,z)x(y:z),c,si,ei,'UniformOutput',false)
newc = 4×1 cell array
{'index'} {'cell' } {'char' } {'or' }
% If si and ei are numeric vectors:
c = {'indexing'; 'a cell array'; 'of character'; 'vectors'};
si = [1; 3; 4; 5];
ei = [5; 6; 7; 6];
newc = arrayfun(@(x,y,z)x{1}(y:z),c,si,ei,'UniformOutput',false)
newc = 4×1 cell array
{'index'} {'cell' } {'char' } {'or' }
% or:
newc = cellfun(@(x,y,z)x(y:z),c,num2cell(si),num2cell(ei),'UniformOutput',false)
newc = 4×1 cell array
{'index'} {'cell' } {'char' } {'or' }
  2 件のコメント
Stephen23
Stephen23 2022 年 3 月 1 日
Why create cell array and transpose?:
si = {1,3,4,5}.';
get rid of the superfluous transpose:
si = {1;3;4;5};
Ludovico Nati
Ludovico Nati 2022 年 3 月 1 日
It works great! Thanks for your help!

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

その他の回答 (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