필터 지우기
필터 지우기

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 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