access elements of vector within struct

조회 수: 5 (최근 30일)
dleal
dleal 2022년 4월 22일
편집: Matt J 2022년 4월 22일
Hi all,
I want to update the values of a vector, within a struct, recursively, in a for loop. In particular, I am receiving real time inputs(yobs, observations in milliseconds for several hours), for different objects, which I am storing within a struct (S, for example) :
yobs = randn(1,100); %vector of observations, which i am receiving one by one
S = struct;
S.A = nan(1,100); %preallocate for speed
for ii = 1:numel(yobs)
temp = S.A;
temp(ii) = yobs(ii);
S.A = temp;
end
Accessing the struct in this way, requires a copy of S.A into temp, which will be slow since the iterations will be over millions of observations.
Alternatively, I could not preallocate S.A, but that will also consume time. Is it absolutely necessary to copy the previous values of S.A into a temporary variable as above? thank you

채택된 답변

Voss
Voss 2022년 4월 22일
"Is it absolutely necessary to copy the previous values of S.A into a temporary variable as above?"
No, it's not necessary.
yobs = randn(1,100); %vector of observations, which i am receiving one by one
S = struct;
S.A = nan(1,100); %preallocate for speed
for ii = 1:numel(yobs)
S.A(ii) = yobs(ii);
end
  댓글 수: 1
dleal
dleal 2022년 4월 22일
thank you _ ... for some reason I thought S.A(ii) would produce a struct array. I keep confusing S(ii).A and S.A(ii)... thank you!

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

추가 답변 (1개)

Matt J
Matt J 2022년 4월 22일
편집: Matt J 2022년 4월 22일
S.A doesn't appear to be playing any role within your loop at all. You could just as easily have done,
temp = nan(1,100); %preallocate for speed
for ii = 1:numel(yobs)
temp(ii) = yobs(ii);
end
S.A = temp;

카테고리

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

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by