提高Matlab函数的性能

Oli*_*ver -2 math performance matlab matrix vectorization

我想改进一个简单的matlab函数.有没有算术方法来实现这个功能?我认为这会表现得更好.

function img_output = cutchannels(img_input, min, max)
[r c l] = size(img_input);
img_output = double(img_input);

for i = 1:r
    for j = 1:c
        for k = 1:l
            if(img_output(i:j:k)> max)
                img_output(i:j:k) = max;
            elseif(img_output(i:j:k) < min)
                img_output(i:j:k) = min;
            end
        end
    end
end
end
Run Code Online (Sandbox Code Playgroud)

ang*_*nor 6

如果我理解正确,这就是你想要做的

function img_output = cutchannels(img_input, min, max)

img_output = double(img_input);
img_output(img_output>max) = max;
img_output(img_output<min) = min;

end
Run Code Online (Sandbox Code Playgroud)

首先,我认为您的索引存在错误:img_output(i:j:k)实际上应该读取img_output(i,j,k)- 这是索引3D数组的方法.

以上是在MATLAB中使用逻辑索引的标准方法(在此处阅读).该声明

img_output>max
Run Code Online (Sandbox Code Playgroud)

返回一个大小等于0/1的大小数组img_output,其中所有元素img_output都大于max1.您可以使用此矩阵作为索引img_output

img_output(img_output>max)
Run Code Online (Sandbox Code Playgroud)

这只选择img_output逻辑索引等于1的条目.然后,您可以为它们分配任何所需的值

img_output(img_output>max) = max
Run Code Online (Sandbox Code Playgroud)

或者,作为附注,对它们进行任何其他操作,例如

img_output(img_output>max) = img_output(img_output>max).^2;
Run Code Online (Sandbox Code Playgroud)