Applying equation to each field in a structure
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
Teja Muppirala
am 16 Aug. 2017
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 Kommentare
Siehe auch
Kategorien
Mehr zu Data Import and Analysis finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!