Zero out values in multiple fields of a struct

Suppose I have
S.ABC0500 = struct('Keys',[1:9],'Values',rand(1,9));
S.ABC0800 = struct('Keys',[1:9],'Values',rand(1,9));
S.ABC0900 = struct('Keys',[1:9],'Values',rand(1,9));
S.Title = 'MyData';
S.Date = datetime('today');
How can I efficiently set all the values to zero? That is, I want to do
S.ABC0500.Values = zeros(1,9);
S.ABC0800.Values = zeros(1,9);
S.ABC0900.Values = zeros(1,9);
The number of ABC variables is large.

댓글 수: 1

"How can I efficiently set all the values to zero"
With more suitable data design: don't force meta-data into fieldnames. A non-scalar structure would likely be better:

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

 채택된 답변

Rich006
Rich006 2023년 5월 8일

0 개 추천

I have found my own answer, but there's probably a more elegant way.
fn = fieldnames(S); % array of S field names including the ABC variables
idx = regexp(fn,'ABC*'); % cell array of 1 or [] depending on whether fn matches 'ABC*'
for k=1:length(fn)
if idx{k}
S.(fn{k}).Values = zeros(1,9);
end
end

댓글 수: 1

Matt J
Matt J 2023년 5월 8일
편집: Matt J 2023년 5월 8일
I would simplify this to,
fn = fieldnames(S);
fn=fn( startsWith( fn ,"ABC"));
for k=1:length(fn)
S.(fn{k}).Values(:) = 0;
end
In particular, avoiding repeated calls to zeros() should speed things up a bit.

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

추가 답변 (1개)

Matt J
Matt J 2023년 5월 5일
편집: Matt J 2023년 5월 5일

0 개 추천

I would recommend a different data organization:
S.Title = 'MyData';
S.Date = datetime('today');
S.ID=["ABC0500", "ABC0500", "ABC0900"]';
S.Values=rand(3,9);
S.Keys=repmat(1:9,3,1);
and then you can simply do,
S.Values(:)=0;

댓글 수: 3

I have to work with the existing variable names and organization. My goal is to create an empty data structure having the same format and organization, that I can later refill with fake test data. I was thinking there should be a way to use regexp to pick out the fields with ABC names and set their values to all zeros.
Matt J
Matt J 2023년 5월 8일
You could do that, but it won't be efficient.
I guess when I said "efficiently" I meant without having to write a separate command for each variable. I only need to do this one time, so speed of execution isn't that important.

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

카테고리

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

태그

질문:

2023년 5월 5일

편집:

2023년 5월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by