简体   繁体   中英

find first and last value for unique julian date

i have a data set similar to the following:

bthd = sort(floor(1+(10-1).*rand(10,1)));
bthd2 = sort(floor(1+(10-1).*rand(10,1)));
bthd3 = sort(floor(1+(10-1).*rand(10,1)));

Depth = [bthd;bthd2;bthd3];
Jday = [repmat(733774,10,1);repmat(733775,10,1);repmat(733776,10,1)];

temp = 10+(30-10).*rand(30,1);

Data = [Jday,Depth,temp];

where I have a matrix similar to 'Data' with Julian Date in the first column, depth in the second, and then temperature in the third column. I would like to find what are the first and last values are for each unique Jday. This can be obtained by:

Data = [Jday,Depth,temp];

[~,~,b] = unique(Data(:,1),'rows');

for j = 1:length(unique(b));
    top_temp(j) = temp(find(b == j,1,'first'));
    bottom_temp(j) = temp(find(b == j,1,'last'));
end

However, my data set is extremely large and using this loop results in long running time. Can anyone suggest a vectorized solution to do this?

use diff :

% for example
Jday = [1 1 1 2 2 3 3 3 5 5 6 7 7 7];
last = find( [diff(Jday) 1] );
first = [1 last(1:end-1)+1];
top_temp = temp(first) ;
bottom_temp = temp(last);

Note that this solution assumes Jday is sorted. If this is not the case, you may sort Jday prior to the suggested procedure.

You should be able to accomplish this using the occurrence option of the unique function:

[~, topidx, ~] = unique(Data(:, 1), 'first', 'legacy');
[~, bottomidx, ~] = unique(Data(:, 1), 'last', 'legacy');

top_temp = temp(topidx);
bottom_temp = temp(bottomidx);

The legacy option is needed if you're using MATLAB R2013a. You should be able to remove it if you're running R2012b or earlier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM