Extend a string within a for loop by values from switch case

2 ビュー (過去 30 日間)
Christian
Christian 2021 年 5 月 10 日
編集済み: Dyuman Joshi 2021 年 5 月 10 日
This switch case works in c. With each pass, the loop finds a letter and assigns it to a binary sequence. The nice thing is, each new binary sequence is simply added (by: +=) to an existing string. Does this also work in matlab?
for (int i = 0; i < sizeInput; i++) {
switch (inputText[i]) {
case ' ':
outputText+= "00000";
break;
case 'A':
outputText+= "00001";
break;
case 'B':
outputText+= "00010";
break;
}
}
For example the inputText is: AB BA, the result should look like: 0000100010000000001000001
I hope you can help me with this.

採用された回答

Dyuman Joshi
Dyuman Joshi 2021 年 5 月 10 日
編集済み: Dyuman Joshi 2021 年 5 月 10 日
No, MATLAB doesn't support Augmented addition, (using +=)
However, you can obtain the same result with a variable, x=x+1; and use dec2bin(x).
If you add strings together in MATLAB, it will give a double (default MATLAB numeric format) output corresponding to the ASCII codes.
You can join strings using join(), or horzcat() (you can also use [ ] to concatenate strings, ['a' 'b'] = 'ab')
  1 件のコメント
Christian
Christian 2021 年 5 月 10 日
Thanks a lot, I did not know that!

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

その他の回答 (1 件)

Stephen23
Stephen23 2021 年 5 月 10 日
編集済み: Stephen23 2021 年 5 月 10 日
Forget about C.
The MATLAB approach is to work with vectors and matrices (which is where the name MATLAB comes from):
inp = 'AB BA';
vec = ' AB';
rpl = ["00000","00001","00010"];
[X,Y] = ismember(inp,vec);
out = join(rpl(Y(X)),'') % string scalar
out = "0000100010000000001000001"
out = [rpl{Y(X)}] % char vector
out = '0000100010000000001000001'

カテゴリ

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