您可以使用以下方法解决此问题find https://www.mathworks.com/help/matlab/ref/find.html, cummin https://www.mathworks.com/help/matlab/ref/cummin.html, 还有一些逻辑索引 https://www.mathworks.com/help/matlab/math/array-indexing.html#MatrixIndexingExample-3。从这个例子开始:
>> u = randi([0 1], 10);
>> u(end, :) = 1
u =
0 0 0 0 1 0 1 0 1 1
1 0 1 1 1 0 0 0 0 1
0 0 0 0 0 1 0 1 1 0
1 1 1 0 1 1 0 0 0 0
0 0 1 0 0 0 0 0 1 0
1 1 1 0 0 0 0 0 0 0
0 1 0 1 0 0 1 1 0 1
1 1 0 1 0 1 1 1 1 1
1 0 0 1 0 0 1 1 1 1
1 1 1 1 1 1 1 1 1 1
以下将做你想做的事:
i = nan(size(u)); % Start with all nan values
[r, ~] = find(u); % Get row indices of non-zero values
i(u ~= 0) = r; % Place row indices in locations of non-zero values
i = cummin(i, 1, 'reverse'); % Column-wise cumulative minimum, starting from bottom
结果:
i =
2 4 2 2 1 3 1 3 1 1
2 4 2 2 2 3 7 3 3 2
4 4 4 7 4 3 7 3 3 7
4 4 4 7 4 4 7 7 5 7
6 6 5 7 10 8 7 7 5 7
6 6 6 7 10 8 7 7 8 7
8 7 10 7 10 8 7 7 8 7
8 8 10 8 10 8 8 8 8 8
9 10 10 9 10 10 9 9 9 9
10 10 10 10 10 10 10 10 10 10
然后你可以计算你的矩阵boo
通过转换i
to a 线性指数 https://www.mathworks.com/help/matlab/math/array-indexing.html#MatrixIndexingExample-2:
index = i+time_size.*repmat(0:(scenario_size-1), time_size, 1); % Create linear index
boo = number(index)./u(index);
或者,您可以计算i
作为从一开始的线性索引:
i = nan(size(u)); % Start with all nan values
index = find(u); % Get linear indices of non-zero values
i(index) = index; % Place linear indices in locations of non-zero values
i = cummin(i, 1, 'reverse'); % Column-wise cumulative minimum, starting from bottom
boo = number(i)./u(i);