How to find the maximum element by length without a loop?

1 回表示 (過去 30 日間)
Daniel
Daniel 2022 年 11 月 24 日
編集済み: John D'Errico 2022 年 11 月 24 日
I have 2 strings: a and b.
How to get the longer one using built-in functions?

採用された回答

Florian Bidaud
Florian Bidaud 2022 年 11 月 24 日
編集済み: Florian Bidaud 2022 年 11 月 24 日
arrayStr = [a,b];
[~,i] = max(strlength(arrayStr));
maxStr = arrayStr(i);
Careful, that works only if a and b are strings, it does not work with char arrays
  1 件のコメント
John D'Errico
John D'Errico 2022 年 11 月 24 日
+1, since your answer may easily be the correct one, depending on the real question. :)

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

その他の回答 (1 件)

John D'Errico
John D'Errico 2022 年 11 月 24 日
編集済み: John D'Errico 2022 年 11 月 24 日
I'm a bit confused as to your question. If you want to choose the longer of two strings, then do as @Florian Bidaud suggests. But perhaps you are looking to know the larger element on an element-by element basis? After all, you talk about loops, and a loop makes little sense in that context.
A = 2:2:12
A = 1×6
2 4 6 8 10 12
B = primes(15)
B = 1×6
2 3 5 7 11 13
To find the element-wise maximum, without a loop, you would do this:
max(A,B)
ans = 1×6
2 4 6 8 11 13
Or, possibly you want to know what is the overall maximum element between both strings? Now you might do this:
max([A,B])
ans = 13
Or, are you asking how to know what is the length of the longer of the two strings? I can probably go on forever with variations on this, since your question is too vague to be sure as to the real question.
The point being, your subject question asks for the meximum element, but then your question asks for the longer of two strings. Which is it?

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by