# Applying monthly coefficients to daily data

3 views (last 30 days)
Nathan Dick on 4 Apr 2017
Commented: JohnGalt on 4 Apr 2017
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

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 CommentsShowHide 1 older comment
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