How can I manipulate with fields in structure.

조회 수: 25 (최근 30일)
Kiryl Zhaliazka
Kiryl Zhaliazka 2022년 3월 4일
답변: Jan 2022년 3월 4일
I have struct s with 96 fields that have different names, each field is 44x1 column of numbers.
is it possible to divide all numbers in each field by some number, or use reshape to make from 44*1 to 11*4 matrix, or for example find max from each field and make a new array from those maximum values.

채택된 답변

Voss
Voss 2022년 3월 4일
You can use structfun() for that:
% creating a struct like yours but with only 3 fields:
s = struct('field1',zeros(44,1),'field2',ones(44,1),'field3',randn(44,1))
s = struct with fields:
field1: [44×1 double] field2: [44×1 double] field3: [44×1 double]
% divide by 7:
s_new = structfun(@(x)x/7,s,'UniformOutput',false)
s_new = struct with fields:
field1: [44×1 double] field2: [44×1 double] field3: [44×1 double]
s_new.field2
ans = 44×1
0.1429 0.1429 0.1429 0.1429 0.1429 0.1429 0.1429 0.1429 0.1429 0.1429
% reshape:
s_new = structfun(@(x)reshape(x,11,4),s,'UniformOutput',false)
s_new = struct with fields:
field1: [11×4 double] field2: [11×4 double] field3: [11×4 double]
% get the max:
s_max = structfun(@max,s)
s_max = 3×1
0 1.0000 2.6450
  댓글 수: 2
Kiryl Zhaliazka
Kiryl Zhaliazka 2022년 3월 4일
Thank you so much!
Voss
Voss 2022년 3월 4일
You're welcome!
If that answers your question, please consider marking the answer as 'Accepted'. Thanks!

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

추가 답변 (1개)

Jan
Jan 2022년 3월 4일
A loop over the field names can achieve this:
s = struct('field1',zeros(44,1),'field2',ones(44,1),'field3',randn(44,1)); % Thanks _
Field = fieldnames(s);
for k = 1:numel(Field)
s.(Field{k}) = s.(Field{k}) / 17;
% Or: s.(Field{k}) = reshape(s.(Field{k}), 4, 11);
end
This is done in structfun also, but the loop runs faster and is easier to read, in my opinion.

카테고리

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