从3D数组中找到值的ind2sub

时间:2018-08-01 17:06:38

标签: matlab multidimensional-array indexing

我有一个数据集time_local,大小为144x91x8845(lon x lat x hour)。我想查找特定时间发生的索引。

data存储数据

time_local存储数据出现的时间。由于时区不同,并非每个144x91面中的所有小时都相同

% One year
first = datenum([num2str(years(y)),'-01-01 00:00:00']);
last = datenum([num2str(years(y)),'-12-31 23:00:00']); 
dt=1/24;  
subset = first:dt:last;

% Find where hour one occurs (want all hours, but starting with 1 hour)
ind = find(time_local == subset(1)); % Hour 1

% Want to save out a new data matrix with the data from hour 1
[a,b,~] = size(time_local);
ind = find(time_local == subset(1)); % Day 1

[x1,y1,z1] = ind2sub(size(time_local),ind);
ind1 = [x1,y1,z1];

data1 = NaN(a,b,length(subset)); % Preallocate new array 
data1(:,:,1) = data(ind1(1,:)); % Pull out data where 

ind给了我线性索引,但是我想知道下标索引,所以我可以将data1保存到每个144x91面为一小时的位置。目前,ind2sub似乎没有找到正确的索引,因为从索引中出来的time_local不正确。

编辑:我尝试了以下操作,但由于保存的time_local1data索引不正确,所以无法正常工作,但是已接近完成。不过,必须有一种更有效的方法。

time_local1 = NaN(a,b,length(subset));
data = NaN(a,b,length(subset));
for a1 = 1:length(subset)
    if isempty(time_local == subset(a1)) == 0
        ind = find(time_local == subset(a1)); % Hour 1
        [x1,y1,z1] = ind2sub(size(time_local),ind);
        for a2 = 1:length(x1)
            time_local1(x1(a2),y1(a2),a1) = time_local(x1(a2),y1(a2),z1(a2));
            data(x1(a2),y1(a2),a1) = data1(x1(a2),y1(a2),z1(a2));
        end
    end
end

1 个答案:

答案 0 :(得分:0)

这可能不是最有效的方法-使用循环-但却有效

    [a,b,~] = size(data1); % Size of data file
    first = datenum([num2str(years(y)),'-01-01 00:00:00']); % Hour one
    last = datenum([num2str(years(y)),'-12-31 23:00:00']);
    dt=1/24;  
    subset = first:dt:last;

    %% Find where hour 1 occurs along the 3rd dimension for every gridcell (matching vector and vector instead of vector and matrix)
    % Pre-allocate
    time_local1 = NaN(a,b,length(subset));
    data = NaN(a,b,length(subset));

    count = 1:24:length(data1); % Set increases for beginning of each day
    for a1 = 1:a % lon
        disp(a1)
        for b1 = 1:b % lat
            ind(a1,b1) = find(time_local(a1,b1,:) == first); % Location of hour one in the 3rd dimension
            ind1 = ind(a1,b1):24:length(data1); % Hours in each day starting from hour one
            for c1 = 1:length(ind1)-2
                %%% Ran once - Checking if the dates I am averaging across
                %%% actually have no missing days 
                % if squeeze(time_local(a1,b1,ind1(c1):ind1(c1)+23)) ~= subset(count(c1):count(c1)+23)'
                %     disp([a1,b1])
                % end

                time_local1(a1,b1,count(c1):count(c1)+23) = time_local(a1,b1,ind1(c1):ind1(c1)+23); % Hourly data 
                data(a1,b1,c1) = nanmean(data1(a1,b1,ind1(c1):ind1(c1)+23)); % Average over one day
                time(a1,b1,c1) = time_local1(a1,b1,count(c1)); % One entry per day
            end
        end
    end