我该如何以更加惯用和有效的方式重新编写此MATLAB代码? [英] How can I re-write this MATLAB code in a more idiomatic and efficient way?
问题描述
这里是要求:输入是一个数字,它将一个图像分成几个相等的部分.例如,如果输入为4,它将返回3个部分:值分别为imgSize/4
imgSize/4 * 2
和imgSize/4 * 3
.
Here is the requirement: the input is a number which will divide an image into several equal part. For example, if the input is 4, it will return 3 parts: the values are the imgSize/4
imgSize/4 * 2
and imgSize/4 * 3
.
如果输入为n
,则它将返回n - 1
元素,如以下实现所示:
If the input is n
, then it will return n - 1
elements, as in the following implementation:
if (colorLevel == 8)
divide_thres = [ round(imgSize/8) round(imgSize/8)*2 round(imgSize/8)*3 round(imgSize/8)*4
round(imgSize/8)*5 round(imgSize/8)*6 round(imgSize/8)*7 ];
elseif (colorLevel == 4)
divide_thres = [ round(imgSize/4) round(imgSize/4)*2 round(imgSize/4)*3 ];
elseif (colorLevel == 3)
divide_thres = [ round(imgSize/3) round(imgSize/3)*2 ];
end
我想允许用户输入2到255之间的值,然后自动生成与该输入相对应的divide_thres
.如何重新编写此代码以提高效率?
I want to allow the user to input a value between 2 and 255, and then automatically generate the divide_thres
corresponding to that input. How can I re-write this code to be more efficient?
推荐答案
您的代码有几个问题:
- 在每种情况下,您都不必要多次将
imgSize
除以相同的因子(而不是一劳永逸). - 您执行了许多手动"标量乘法,但是您可以将标量值乘以由范围
1 : colorLevel - 1
生成的向量. -
由于可以很容易地从
colorLevel
的值计算出生成的divide_thres
向量的长度,因此无需在if
语句中分别处理每种情况.
- In each case, you unnecessarily divide
imgSize
by the same factor multiple times (instead of just once and for all). - You perform many "manual" scalar multiplications, but you could simply multiply the scalar value by a vector generated by the range
1 : colorLevel - 1
. Because the length of the resulting
divide_thres
vector can be easily computed from the value ofcolorLevel
, there is no need to treat each case separately in anif
statement.
此外,即使在imgSize
= 3
,4
和8
情况下,即使必须以不同的方式计算长度,您也最好使用switch
语句代替if
语句,因为前者可以为您节省每次编写imgSize == ...
的麻烦,因为它容易出错,并且会产生某种形式的代码重复.
Moreover, even if you had to compute the length in a different manner for the cases imgSize
= 3
, 4
, and 8
, you would be better off using a switch
statement instead of an if
statement, because the former would save you the trouble of writing imgSize == ...
each time, which is prone to errors and a form of code duplication.
这是一种非常简化的方法:
Here's a much simplified approach:
if 2 <= colorLevel && colorLevel <= 255
divide_thres = round(imgSize / colorLevel) * (1 : colorLevel - 1);
else
error('invalid colorLevel value') % (or some other informative message)
end
这篇关于我该如何以更加惯用和有效的方式重新编写此MATLAB代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!