Look for Values in next column (max. 5 Values next)

1 次查看(过去 30 天)
I have a variable 1080x2. If there is a number (unequal 0) in column 1 (A), it should look in the 2nd column (B) up to 5 rows/values (not equal 0) further and take the last value (which is not equal 0) and add it to a new column (C). If there is no value found within 5 rows, then insert the value from 1st column (A).
The example datas are attached. I think ts more understandable as a excel example: Yellow are the values from 1st column and green are the founded values.
0 0
0 0
0 0
2 2
0 0
0 3
0 -5
0 0
0 0
0 0
-4 0
0 1
0 9
0 0
0 0
0 0
-1 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0

采纳的回答

DGM
DGM 2021-5-1
编辑:DGM 2021-5-1
This could be done without a loop, but it gets clumsy and awkward. I'll just use a loop.
A = [0 0;
0 0;
0 0;
2 2;
0 0;
0 3;
0 -5;
0 0;
0 0;
0 0;
-4 0;
0 1;
0 9;
0 0;
0 0;
0 0;
-1 0;
0 0;
0 0;
0 0;
0 0;
0 0;
0 0;
0 0];
nahead = 5; % number of elements to look ahead
% add new column
A = [A,zeros(size(A,1),1)];
% find nonzero elements of col1
c1occurrence = find(A(:,1)~=0);
for occ = 1:numel(c1occurrence)
% make sure to limit the index so it doesn't run off the end
regionahead = A(min(c1occurrence(occ)+(0:nahead-1),size(A,1)),2);
lastvalloc = find(regionahead~=0,1,'last'); % location of last nz value
if isempty(lastvalloc)
A(c1occurrence(occ),3) = A(c1occurrence(occ),1);
else
A(c1occurrence(occ)+lastvalloc-1,3) = A(c1occurrence(occ)+lastvalloc-1,2);
end
end
A
gives
A =
0 0 0
0 0 0
0 0 0
2 2 0
0 0 0
0 3 0
0 -5 -5
0 0 0
0 0 0
0 0 0
-4 0 0
0 1 0
0 9 9
0 0 0
0 0 0
0 0 0
-1 0 -1
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0

更多回答(1 个)

Jan
Jan 2021-5-1
编辑:Jan 2021-5-1
FileData = load('example.mat');
Data = FileData.numbers;
index = find(Data(:, 1));
for k = 1:numel(index)
c = index(k);
b = Data(c:c+4, 2); % Safer: Data(c:min(c+4, height(Data)), 2)
last = find(b, 1, 'last');
if isempty(last)
Data(c, 3) = Data(c, 1);
else
Data(c + last - 1, 3) = b(last);
end
end

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by