Largest value near a 0
Show older comments
Hi all! I got stuck in an assignment, that is the following: write a function that takes as input a vector and outputs the largest adjacent value near a 0. So that [ 1 4 6 2 8 0 7 3 4 6 0 1] becomes y = 8. I wrote the following function
function y = nearZero(x)
for i = 1:length(x);
b = [];
if x(i) == 0 && x(i) ~= x(end)
b(i) = x(i-1)
b(i+1) = x(i+1)
else
b(i) = NaN;
end
end
y = b
end
But I get a vector of 0s. Could you give me a hint in how to make this code work? Thanks
Accepted Answer
More Answers (1)
Image Analyst
on 2 Jul 2017
Well your homework probably doesn't expect you to use image processing functions like imdilate(), which is a local max function, but anyway, it can be done in 2 lines of code if you do use it:
v = [ 1 4 6 2 8 0 7 3 4 6 0 1]
mask = imdilate(v == 0, ones(1,3)) % Find 0's and expand by 1 element in each direction.
largestValue = max(v(mask))
Categories
Find more on Operators and Elementary Operations 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!