从另一个循环中选择相应的值以在后续循环

时间:2015-12-18 06:39:35

标签: matlab

我是地球科学家,对河流盆地宏观尺度形态参数感兴趣。我正在从Excel工作表中构建一个简单的渐变Stream Gradient索引。我写了一个简单的代码如下:

data = 'SL.xlsx';
headers = xlsread(data);
lat = headers (:,1);
long = headers (:,2);
elevation = headers (:,3);
numberofelement = numel (lat);

% To calculate the intermideate distacne between two points

for i=2:numberofelement
intdistance (1)=0;
intdistance (i) = sqrt((lat (i)-lat (i-1))^2+ (long (i)-long (i-1))^2);
end

% Cumulative distacne in km

cumdist (1)=0

for j=2:numberofelement
cumdist(j)=cumdist(j-1)+intdistance (j);
cumdistkm (j)= cumdist(j)/1000;
end

% Average SL index (or graded river gradient
gradedslindex = (elevation (1)- elevation (numberofelement))/log(cumdistkm(numberofelement))

我无法执行后续步骤。接下来的步骤包括一些计算:

假设数据看起来像

Cumdist Elevation

0.25     500
2.1      480
4.2      470
6.8      450
7.5      430
8.2      420
9.1      410
10.1     400

1)在cumdistkm变量中,我必须每5 km进行一次分段。如果没有5公里的值,我必须为cumdist选择最接近的较低值。因此,对于这些数据,必须采用4.2和9.1。

2)然后计算部分将是高程(最后) - 升高(第一)(对于该特定范围)并除以In(cumdistkm(最后)) - In(cumdist(first))(对于相同的行索引) )。

我无法定期选择这些参数。一个小提示将非常有用。

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用cumsum功能查找cumdist

cumdist_km = [0; cumsum(intdistance)/1000];  %calculate cumdist in km

我会创建一个函数并将其粘贴到文件findIndicesBelowIncrement.m中。可能有一种更为流畅的方式来做到这一点,但这应该非常快并且有效(因为我理解你所要求的)。

function indices = findIndicesBelowIncrement(cumdist_km, km_increment)
% indices = findIndicesForBelowIncrement(cumdist_km, km_increment)
%        cumdist_km  : sorted array of distances
%        km_increment: we will find index of cumdist_km for each 
%                      multiple of increment such that distance is
%                      at or below the multiple of the increment

indices = NaN(ceil(cumdist_km(end) / 5), 1);  % we know endpoint, lets init smart
j = 1;
for i=2:length(cumdist_km)             % iterate through array
  if(cumdist_km(i) > j * km_increment) % we have just passed increment multiple
    indices(j) = i - 1;                % previous index is what we want
    while(cumdist_km(i) > j * km_increment) % handle case value skips ahead
                  % note: well end up with a NaN in indices for every skip
      j = j + 1   % normal is 1 increment. skip is > 1
    end
  end
end
indices(end) = length(cumdist_km);     

然后回到您的主脚本中,您可以这样做:

five_km_indices = findIndicesBelowIncrement(cumdist_km, 5);
dist_5kminc = cumdist_km(five_km_indices);
elev_5kminc = elevations(five_km_indices);

然后对dist_5kminc和elev_5kminc进行任何计算。