find length of a field within structure and specific values

조회 수: 93 (최근 30일)
Nicolas
Nicolas 2017년 1월 26일
답변: George Abrahams 2022년 12월 30일
Hello,
I create a structure using the script below. I would like to know how can I find the length of each field and how can I find specific values within them?
Thank you very much
for ii = 1 : length(SplitDom);
Name_DomCoord = strcat('DomCoord',num2str(ii));
variable.(Name_DomCoord) = model.geom(Name_Geom).obj(SplitDom(ii)).getVertexCoord();
end

채택된 답변

Sruthi Geetha
Sruthi Geetha 2017년 1월 30일
"getfield" function can be used to get the value of each field in the array. Refer the following link to know how to use the "getfield" function:
https://www.mathworks.com/help/matlab/ref/getfield.html
The length of each field in the array can be found by using "structfun" in combination with "numel" function.
For example:
clear s; % save old stuff!
s.a=1:10;
s.b=pi;
s.c=magic(3);
r=structfun(@numel,s)
%{
% r =
10
1
9
%}

추가 답변 (1개)

George Abrahams
George Abrahams 2022년 12월 30일
The problem with the structfun approach is that the array output relates to the structure's field order. If you don't want to rely on a particular field order and/or want to keep the field names for readability, you could use my fieldfun function on File Exchange / GitHub. It's like structfun, but it outputs a structure with the same fields as the input structure.
variable = struct( 'DomCoord1', 1, 'DomCoord2', [2 3], ...
'DomCoord3', [4 5 6] );
fieldfun( @numel, variable )
% ans = struct with fields:
% DomCoord1: 1
% DomCoord2: 2
% DomCoord3: 3

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by