Conditionally replace numerical Array with Strings

1 回表示 (過去 30 日間)
Metin Akyol
Metin Akyol 2021 年 11 月 22 日
コメント済み: Metin Akyol 2021 年 11 月 22 日
I have a simply array with 0s and 1s and I would like to replace each element conditionally with a string like so:
old_array = [0 1 0 0 1]
new_array = ["string0" "string1" "string0" "string0" "string1"]
I have tried this, but ended up with NaNs:
old_array(old_array>0)=string("string1")

回答 (1 件)

Dave B
Dave B 2021 年 11 月 22 日
This is happening because old_array is an array of doubles, you can't have a mix of strings and doubles in a regular (i.e. not cell) array.
You can convert an array to string and replace all of the values
old_array = [0 1 0 0 1];
old_array = "string" + string(old_array)
old_array = 1×5 string array
"string0" "string1" "string0" "string0" "string1"
Or convert the array to string and just replace some of the values (and still keep everything string):
old_array = [0 1 0 0 1];
ind = old_array>0;
old_array = string(old_array);
old_array(ind) = "string1"
old_array = 1×5 string array
"0" "string1" "0" "0" "string1"
Or you can use a cell array to mix and match types:
old_array = [0 1 0 0 1];
ind = old_array>0;
old_array = num2cell(old_array);
old_array(ind)={"string1"}
old_array = 1×5 cell array
{[0]} {["string1"]} {[0]} {[0]} {["string1"]}
  1 件のコメント
Metin Akyol
Metin Akyol 2021 年 11 月 22 日
Perfect, solved my problem. Thank you for clarifying.

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

カテゴリ

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by