Clear Filters
Clear Filters

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

6 views (last 30 days)
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 Comment
Stephen23
Stephen23 on 23 May 2024
"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"

Sign in to comment.

Answers (1)

Cris LaPierre
Cris LaPierre on 22 May 2024
Edited: Cris LaPierre on 23 May 2024
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 Comment
VBBV
VBBV on 23 May 2024
@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'

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2024a

Community Treasure Hunt

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

Start Hunting!