How to create a string array with long strings that continue to a new line?

35 ビュー (過去 30 日間)
Tuukka Takala
Tuukka Takala 2021 年 4 月 8 日
コメント済み: Tuukka Takala 2021 年 4 月 8 日
I ran into curious behavior with Matlab R2020b, when I tried to manually create a string array with really long strings that continue to a new line.
In the below examples I have shortened the strings for the sake of readability.
I was surprised that the following input does not concatenate the double "aa"s and "cc"s into individual strings "aaaa" and "cccc".
["aa" ...
"aa", "bbbb", "cc" ...
"cc"]
Instead you get:
ans =
1×5 string array
"aa" "aa" "bbbb" "cc" "cc"
I also tried the following, which results in to a string instead of string array:
['aa' ...
'aa', 'bbbb', 'cc' ...
'cc']
ans =
'aaaabbbbcccc'
Is there a nice way to get what I want, i.e:
1×5 string array
"aaaa" "bbbb" "cccc"
Currently I'm building the string array by adding a new string in separate statements, which is not very elegant.

採用された回答

Jan
Jan 2021 年 4 月 8 日
編集済み: Jan 2021 年 4 月 8 日
This is not curious, but the expected behaviour. Matlab inserts commas for separating the elements of a vector automatically.
Use + to concatenate strings:
["aa" + ...
"aa", "bbbb", "cc" + ...
"cc"]
ans = 1×3 string array
"aaaa" "bbbb" "cccc"
Note that 'abc' is a "char vector", not a "string". Confusingly {'abc'} is called a "cell string", although it is a "cell array of chat vectors". The cause of this confusion is that the "string" class has been introduced in 2016 and the term "string" was used for char vectors before.
With char vectors use the concatenation operator [ ] to join the subvectors and create a cell array using { }:
{['aa' ...
'aa'], 'bbbb', ['cc' ...
'cc']}
  1 件のコメント
Tuukka Takala
Tuukka Takala 2021 年 4 月 8 日
Thanks for the thorough answer! I actually tried the + operator, but only with char vectors ['aa' + 'aa'] which just summed the numerical representations of the characters...

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

その他の回答 (1 件)

Fangjun Jiang
Fangjun Jiang 2021 年 4 月 8 日
編集済み: Fangjun Jiang 2021 年 4 月 8 日
s=["aa"+ ...
"aa", "bb"+ ...
"bb"]
s =
1×2 string array
"aaaa" "bbbb"

カテゴリ

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