Largest value near a 0
이전 댓글 표시
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
채택된 답변
추가 답변 (1개)
Image Analyst
2017년 7월 2일
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))
카테고리
도움말 센터 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!