Applying equation to each field in a structure
11 次查看(过去 30 天)
显示 更早的评论
I have a structure from an ocean buoy that I am trying to manipulate. The structure has 4 fields air temperature, wind speed, sst, and qa. I want to apply an equation to each field without having to copy past 4 times. I just know there has to be a better way
for i = 1:365
airt(i) = 1/K*sum(buoy.airt((i-1)*K+1 : i*K)) ;
sst(i) = 1/K*sum(buoy.sst((i-1)*K+1 : i*K)) ;
wspd(i) = 1/K*sum(buoy.wspd((i-1)*K+1 : i*K)) ;
qa(i) = 1/K*sum(buoy.qa((i-1)*K+1 : i*K)) ;
end
0 个评论
回答(2 个)
Teja Muppirala
2017-8-16
For 4 variables, copy/pasting seems doable, but if you had a lot more I can see how it could be cumbersome.
This is a solution that uses STRUCTFUN and ARRAYFUN. We generate a new struct "result" that has all the new values for each variable:
%%Make some fake random data
K = 10; % For example, K = 10
buoy = struct('airt',randn(1,365*K), 'sst',randn(1,365*K),'wspd',randn(1,365*K),'qa',randn(1,365*K))
%%Method 1, use a loop. Simple to understand, but hard to scale.
for i = 1:365
airt(i) = 1/K*sum(buoy.airt((i-1)*K+1 : i*K)) ;
sst(i) = 1/K*sum(buoy.sst((i-1)*K+1 : i*K)) ;
wspd(i) = 1/K*sum(buoy.wspd((i-1)*K+1 : i*K)) ;
qa(i) = 1/K*sum(buoy.qa((i-1)*K+1 : i*K)) ;
end
%%Method 2, Using STRUCTFUN and ARRAYFUN.
% Admittedly not very readable... but at least you don't have to copy/paste for every variable
innerFunction = @(X,ii) 1/K*sum(X((ii-1)*K+1 : ii*K)) ;
result = structfun( @(X) arrayfun(@(ii) innerFunction(X, ii),1:365), buoy, 'uniform',false) % <-- Your answer
% Verify that they do indeed give you the same answers.
isequal(airt, result.airt) % TRUE
isequal(sst, result.sst) % TRUE
isequal(wspd, result.wspd) %TRUE
isequal(qa, result.qa) %TRUE
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!