Need to use cellfun for returning index of array

2 ビュー (過去 30 日間)
Thulasi Durai Durai Samy
Thulasi Durai Durai Samy 2012 年 7 月 9 日
Hello
I need to find index for string in structures when compare with required string.
I use the following code
for i=1:numel(LD)
if strcmp('Lam1',LD(i).Name)
break;
end
end
where i = array index.
Here I will find the index for string residing in LD(:).Names
is their any easy way to find the index using cellfun
I tried like this cellfun(@strcmp,'Lam1',LD(:).Names)
should return the index, correct me I am worng.
  2 件のコメント
Jan
Jan 2012 年 7 月 9 日
編集済み: Jan 2012 年 7 月 9 日
You forgot to explain the type of LD.Name: Are they strings or cell strings? And btw., is it LD.Name or LD.Names in plural? I avoid corresponding programming errors by the simple convention:
  • All names in singular
  • When it matters if a variable is a scalar entity or a list of objects: aMyObject and MyObjectList.
I do not think that this is nicer, but avoiding sources of bugs is more important, especially because useful programs tend to grow.
Thulasi Durai Durai Samy
Thulasi Durai Durai Samy 2012 年 7 月 9 日
thanks for your nice comments

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

採用された回答

Jan
Jan 2012 年 7 月 9 日
編集済み: Jan 2012 年 7 月 9 日
No need for cellfun or arrayfun:
index = find(strcmp('Lam1', {LD.Name}), 1);
{LD.Name} is efficient, because it creates shared data copies only - this means that the actual strings are not duplicated.
  2 件のコメント
Thulasi Durai Durai Samy
Thulasi Durai Durai Samy 2012 年 7 月 9 日
ya, it works !! what actually happening in side can you brief me. why to pass 1 as argument for 'find' function.
Jan
Jan 2012 年 7 月 9 日
find(., 1) searchs for the first occurrence only, see help find. On one hand this is a little bit faster, if LD is really large. On the other hand it replicates the behaviour of your function, which breaks after the first occurence also.

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

その他の回答 (2 件)

F.
F. 2012 年 7 月 9 日
try this :
regexp( { LD(:).Name } , 'Lam1' , 'once )
it's to find the first occurance of Lam1 in the cell array { LD(:).Name }

Walter Roberson
Walter Roberson 2012 年 7 月 9 日
編集済み: Walter Roberson 2012 年 7 月 9 日
cellfun(@(S) strcmp('Lam1',S), {LD.Name} )

カテゴリ

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