How to Check if Element of Array Exists?

78 ビュー (過去 30 日間)
Ted Baker
Ted Baker 2019 年 11 月 27 日
編集済み: Image Analyst 2019 年 11 月 27 日
I have an array of strings which varies in size depending on the number of words in a file name. One file might result in an array of animals[dog, cat, fish], whilst the next might be animals[horse, bird, dog, cat, snake]. If, say, the fifth element of animals is snake, then I will have the program do something. However, this only works if the array is at least 5 elements long. Using my first example would result in an Error, as it only has three elements. Is there a way to check if the array has x elements before I check the xth element?

採用された回答

Image Analyst
Image Analyst 2019 年 11 月 27 日
編集済み: Image Analyst 2019 年 11 月 27 日
Try length()
animals1 = ["dog", "cat", "fish"]
animals2 = ["horse", "bird", "dog", "cat", "snake"]
x = 5
if length(animals2) >= x
% animals2 has at least x strings in it, so do something.
if strcmpi(animals2(x), 'snake')
% Do something.
fprintf('animals2(%d) = "%s".\n', x, animals2(x));
end
end

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by