简体   繁体   English

MATLAB:返回数组中的最大数字?

[英]MATLAB: Return the largest number in an array?

I'm new to MATLAB (and this website!) and I needed some help with a problem I had been assigned for class. 我是MATLAB(以及该网站!)的新手,我需要一些有关分配给课堂的问题的帮助。 I searched this website for similar MATLAB problems, but I didn't come across any. 我在该网站上搜索了类似的MATLAB问题,但没有发现任何问题。 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. 我试图使用我在网上找到的稍微复杂的函数来解决该问题,它似乎可以在MATLAB上运行。 However, it won't work on our automated online MATLAB grading system as the command "imdilate" isn't recognized: 但是,由于无法识别“ imdilate”命令,因此无法在我们的在线MATLAB自动评分系统上使用:

  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! 谢谢您的帮助,我非常感谢!

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM