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

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

DGM
DGM il 1 Mag 2021
Modificato: DGM il 1 Mag 2021
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

Più risposte (1)

Jan
Jan il 1 Mag 2021
Modificato: Jan il 1 Mag 2021
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

Categorie

Scopri di più su Operating on Diagonal Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by