フィルターのクリア

Indexing array of strings to the full string instead of one letter

6 ビュー (過去 30 日間)
Nancy Lindsey
Nancy Lindsey 2024 年 5 月 22 日
編集済み: Cris LaPierre 2024 年 5 月 23 日
Here is my array of strings:
propnames = ['density', 'entropy', 'enthalpy', 'viscosity', 'Prandtl number', 'thermal conductivity']
I'm trying to index to a particular string, but I can't figure out how to get it to index the entire string instead of just one letter. For instance, "propnames(3)" returns 'n' (the 'n' in 'density') when I want it to return the string 'enthalpy'. Does anyone know how to do this? I'd like to use a for loop from i = 1:6 to access each of these strings independently.
Thank you!
  1 件のコメント
Stephen23
Stephen23 2024 年 5 月 23 日
"Indexing array of strings to the full string instead of one letter"
Because you used single quotes you defined character vectors (aka character arrays), which are very simply arrays of characters (much like numeric arrays are simple arrays of numbers), not strings. Because square brackets are a concatenation operator, your code concatenates those character vectors together:
propnames = ['density', 'entropy', 'enthalpy', 'viscosity', 'Prandtl number', 'thermal conductivity']
propnames = 'densityentropyenthalpyviscosityPrandtl numberthermal conductivity'
and is exactly equivalent to writing this:
propnames = 'densityentropyenthalpyviscosityPrandtl numberthermal conductivity'
propnames = 'densityentropyenthalpyviscosityPrandtl numberthermal conductivity'
which is unlikely to be what you want. Most likely you should be using actual strings, e.g. by using double quotes:
propnames = ["density", "entropy", "enthalpy", "viscosity", "Prandtl number", "thermal conductivity"]
propnames = 1x6 string array
"density" "entropy" "enthalpy" "viscosity" "Prandtl number" "thermal conductivity"

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

回答 (1 件)

Cris LaPierre
Cris LaPierre 2024 年 5 月 22 日
編集済み: Cris LaPierre 2024 年 5 月 23 日
In that case, use strings (double quotes) instead of character arrays (single quotes).
propnames = ["density", "entropy", "enthalpy", "viscosity", "Prandtl number", "thermal conductivity"]
propnames = 1x6 string array
"density" "entropy" "enthalpy" "viscosity" "Prandtl number" "thermal conductivity"
propnames(3)
ans = "enthalpy"
  1 件のコメント
VBBV
VBBV 2024 年 5 月 23 日
@Nancy Lindsey you could also use a cell array to access the desired element
propnames = {'density', 'entropy', 'enthalpy', 'viscosity', 'Prandtl number', 'thermal conductivity'}
propnames = 1x6 cell array
{'density'} {'entropy'} {'enthalpy'} {'viscosity'} {'Prandtl number'} {'thermal conductivity'}
propnames{3}
ans = 'enthalpy'

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

カテゴリ

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

タグ

製品


リリース

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by