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

조회 수: 2 (최근 30일)
Tommy Schumacher
Tommy Schumacher 2021년 4월 30일
댓글: Tommy Schumacher 2021년 5월 1일
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에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by