Applying monthly coefficients to daily data

1 view (last 30 days)
Sorry if the question is elementary but I am trying to do a daily soil moisture balance for a long dataset but am using monthly crop coefficients. I have a column in my main array where I have used the "month(A)" function and I have made a month column in the array storing my coefficient.
I want to apply the corresponding co-efficient to the correct month for each day of the ~100 years. The following code does the job but am new to MATLAB and hoping to find something neater.
Where Data(:,n) are the appropriate columns of the main dataset and kcT(:,n) are columns in the array containing co-efficients with the corresponding month.
for i=1:12
for j = 1 : length(Data(:,1))
if Data(j,4)==kcT(i,2)
DID(j,1)=Data(j,2)*kcT(i,1);
end
end
end

Accepted Answer

JohnGalt
JohnGalt on 4 Apr 2017
The key to a simpler and faster implementation of this is knowing that you can construct an array using an array of indices... For example
array1 = [1 3 5 7 9]
newArrayIndices = [2 2 2];
array1(newArrayIndices) % will be = [3 3 3]
So in this case, if we assume that kcT is in order ie.
[ .5 1
.3 2
.4 3
...
.38 12]
then we can just use the coeff column to construct an array the same size as Data which will have all the coefficients:
monthlyCoeffArray = kcT(Data(:,4,1);
And the whole piece of code becomes...
monthlyCoeffArray = kcT(Data(:,4,1);
DID = Data(j,2).*monthlyCoeffArray; % note the dot-multiply
No need for any for-loops.
  2 Comments
Nathan Dick
Nathan Dick on 4 Apr 2017
Thanks for the quick reply John, that is exactly what I was after. Thanks also for explanation, don't like using code if I don't know how it works. Am I right in thinking that as the actual moisture balance will require a loop due to the fact that it is dependent on the previous time step, or is there a function which has been designed for that situation?
JohnGalt
JohnGalt on 4 Apr 2017
no prob - glad to help.
I'm not sure I understand the question... you need to use a shifted version of the DID variable? if so just shift the index to realign i.e.
Vals = 1:10:
prevDayVals = Vals(1:end-1);
currentDayVals = Vals(2:end);
failing that, a for-loop isn't so bad... it's great to avoid when possible but can make the code much more readable

Sign in to comment.

More Answers (0)

Categories

Find more on Performance and Memory in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!