choose B or C or D if A does not exist - how to write this?

조회 수: 2 (최근 30일)
Tomaszzz
Tomaszzz 2024년 7월 28일
댓글: Paul 2024년 7월 28일
Hi all,
I have the following:
switch joint
case 'Knee'
prox = 'HipJC';
dist = 'LEPI';
wand = 'THPA' ;
end
side = {'R','L'};
for i = 1:length(side)
wandMk = data.([side{i},wand]).line;
end
I got the following error: Unrecognized field name "LTHPA", which is because 'LTHPA' does not exist in my structure.
I could use 'THPP' or 'THDA' or 'THDP' instead of 'THPA', because I know these exist. Hence, how could I rewrite the above for this to run?
For example:
if 'THPA' does not exist then
wand = 'THDA' or 'THDA' or 'THDP'
Thanks!

채택된 답변

Paul
Paul 2024년 7월 28일
Create an example structure
data.THDA = 1;data.THPP = 2;data.THDP = 3;
Use fieldnames to get the fields of data
fnames = fieldnames(data)
fnames = 3x1 cell array
{'THDA'} {'THPP'} {'THDP'}
Field to test
wand = "LTHPA"
wand = "LTHPA"
Reassign if invalid field
if ~any(strcmp(wand,fnames))
wand = "THDA"
end
wand = "THDA"
data.(wand)
ans = 1
  댓글 수: 1
Paul
Paul 2024년 7월 28일
Use isfield instead of strcmp/fieldnames Thanks @Stephen23! How did I not know about that function (rhetorical question)?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by