Look for Values in next column (max. 5 Values next)
Show older comments
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

Accepted Answer
More Answers (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
1 Comment
Tommy Schumacher
on 1 May 2021
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!