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

6 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

产品


版本

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by