From the example provided, it appears you want to calculate average temperatures for specific dates by grouping the temperatures by their respective dates, resulting in a two-column matrix ‘med’.
Initially, the code you have will fail with an "out of array index" error at the line:
tem2=tem(:,iyy2);
This error occurs because ‘tem’ has only 2 columns, while ‘iyy2’ might not be restricted to this column size. It seems you intended to use:
tem2 = tem(iyy2, :);
After correcting this, you can actually verify that ‘med’ also does not contain all ‘NaN’ values by using:
all(isnan(med))
This is because the indices, where the loop successfully matches a date in the date vector, will contain some average values.
However, this approach will not produce the desired output as illustrated in your example. A more precise and computationally efficient method involves identifying the indices of duplicate dates in the date vector first. This can be done using the 'unique' function from MATLAB. Then, calculate the average of the temperatures at those indices for both columns. Pre-allocating the resultant vector can further reduce computation time by avoiding size changes during each loop iteration. A sample code to achieve this would look like:
date=[yy mm dd]
[unique_dates,~,idx]=unique(date,'rows')
Atemp = zeros(size(unique_dates,1),2);
for i = 1:size(idx)
index = idx(i);
indices = (idx==index)
if isempty(tem(indices,:)) || (Atemp(index)~=0)
continue
end
if size(indices,1) > 1 %implies presence of duplicates
Atemp(index,:) = mean(tem(indices,:));
else
Atemp(index,:) = tem(indices,:);
end
end
The resulting ‘Atemp’ aligns with the expected ‘med’ output, calculated with the dates arranged in sorted order.
For more information about 'unique', you can access its documentation page by entering the following command in the MATLAB Command Window:
doc unique
Hope this helps!