checking if field values in a single struct are identical

Hello,
I have a struct (S) with 13 fields. Each field has a 'density' column. I want to do an if statement which checks if all the values in the density columns are the same for each field (all 13 of them) i.e. density vals in field 1 = density vals in field 2 etc
if...(need help with this line)
disp('same altitude')
else
disp('different heights')
end
thank you

댓글 수: 1

Jan
Jan 2023년 1월 19일
편집: Jan 2023년 1월 19일
What does this mean: "Each field has a 'density' column." Do the fields contain tables? Or is "density" the name of a subfield containing a clumn vector?
Prefer to post some Matlab code, which creates some small example data.

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

 채택된 답변

Jan
Jan 2023년 1월 19일
Depending on how the inputs look exactly, maybe:
FieldC = struct2cell(S);
Eq = true;
for k = 2:numel(FieldC)
if ~isequal(FieldC{k}.density, FieldC{1}.density)
Eq = false;
break;
end
end
There are shorter methods, but please explain at first exactly, what the inputs are.

댓글 수: 3

Thank you so much. Sorry I forgot to mention that each of the fields in the struct are a table and each table contains a 'density' column. I want to check if the density values in field 1 = density values in field 2....field n.
I assume, the shown code works for table objects also.
yes, it does! many thanks

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2023년 1월 19일
density_cell = structfun(@(C) {C.density}, YourStruct);
EQ = isequal(density_cell{:});
No explicit loop needed (but structfun is arguably a hidden loop.)

카테고리

도움말 센터File Exchange에서 Structures에 대해 자세히 알아보기

제품

릴리스

R2021b

질문:

2023년 1월 19일

댓글:

2023년 2월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by