0

I'm new to MATLAB (and this website!) and I needed some help with a problem I had been assigned for class. I searched this website for similar MATLAB problems, but I didn't come across any. The problem is asking the user to return the biggest number which is next to a zero. In other words, write a function which takes a list/array of numbers as input and returns the largest number which is adjacent to a zero. For instance, if

a=[1 -2 3 4 0 5 6 0 -7], Output: y=6.

I tried to solve the problem using a somewhat complex function I found online, and it seems to work on MATLAB. However, it won't work on our automated online MATLAB grading system as the command "imdilate" isn't recognized:

  x=[1 2 0 4 5 -6 0 7 0 8]
  zero_mask = (x == 0);
  adjacent_to_zero_mask = imdilate(zero_mask, [1 0 1]);
  max_value_adjacent_to_zero = max(x(adjacent_to_zero_mask));
  y=max_value_adjacent_to_zero

I wanted to ask, is there is much simpler method of solving this problem not involving "imdilate" or other similar functions? Thank you for your help, I really appreciate it!

1 Answers1

1

I came up with a dirty solution:

a=[0 1 -2 3 4 0 5 6 0 -7];
I=find(a==0);
I=unique([I+1,I-1]);
I=I((I>0)&(I<=length(a)));
output = max(a(I));
tashuhka
  • 5,028
  • 4
  • 45
  • 64
  • Sometimes, dirty is good :D I tried your code, and it worked flawlessly. I had tried using `unique` before, but I don't think I had set up the command correctly. Your help is truly appreciated! – John Wayne's Stunt Double Jul 07 '13 at 17:03
  • @JohnWayne'sStuntDouble Actually the unique is not required. The code will still work if you omit it: `I=[I+1,I-1]` (Regardless of `a`) – Dennis Jaheruddin Jul 08 '13 at 08:24
  • @DennisJaheruddin is rigth. I included "unique" just to avoid repeated indices, but the final result would be the same. – tashuhka Jul 08 '13 at 11:06