本文介绍了MATLAB 中的矢量化简介 - 有什么好的教程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关在 MATLAB 中进行矢量化(循环)的任何好的教程.

I'm looking for any good tutorials on vectorizing (loops) in MATLAB.

我有一个非常简单的算法,但它使用了两个 for 循环.我知道矢量化它应该很简单,我想学习如何做到这一点,而不是向您询问解决方案.

I have quite simple algorithm, but it uses two for loops. I know that it should be simple to vectorize it and I would like to learn how to do it instead of asking you for the solution.

但是为了让您知道我遇到了什么问题,以便您能够建议展示如何解决类似问题的最佳教程,以下是我的问题的概述:

But to let you know what problem I have, so you would be able to suggest best tutorials that are showing how to solve similar problems, here's the outline of my problem:

B = zeros(size(A));    % //A is a given matrix.
for i=1:size(A,1)
   for j=1:size(A,2)
      H = ... %// take some surrounding elements of the element at position (i,j) (i.e. using mask 3x3 elements)
      B(i,j) = computeSth(H); %// compute something on selected elements and place it in B
   end
end

所以,我不是在寻求解决方案.我要一个很好的教程,在 MATLAB 中向量化循环的例子.我想学习如何做并自己做.

So, I'm NOT asking for the solution. I'm asking for a good tutorials, examples of vectorizing loops in MATLAB. I would like to learn how to do it and do it on my own.

推荐答案

以下是我经常链接到的一些 MathWorks 教程作为该主题的参考:

Here are a couple of MathWorks tutorials I often link to as references on the subject:

这是 Loren 的一篇博文,其中对特定示例问题的代码矢量化进行了很好的演练:

And here's one of Loren's blog posts that has a nice walkthrough of code vectorization for a particular sample problem:

您作为示例给出的特定类型的问题,涉及处理给定矩阵的子矩阵,可以以不同的方式进行矢量化,这在很大程度上取决于您正在执行的操作类型.您可以使用 CONV2FILTER2 而不是嵌套的 for 循环.Image Processing Toolbox 中还有许多处理矩阵的邻域和块处理,例如 NLFILTERBLOCKPROC.这些函数的文档应该可以帮助您弄清楚如何使用它们作为矢量化代码的一种方式.

The particular type of problem you gave as a sample, which involves processing submatrices of a given matrix, could be vectorized in different ways depending greatly on what sort of operation you are doing. You may be able to use CONV2 or FILTER2 instead of your nested for loops. There are also a number of functions in the Image Processing Toolbox that handle neighborhood and block processing of matrices, such as NLFILTER and BLOCKPROC. The documentation for these functions should help you figure out how to use them as a way to vectorize your code.

这篇关于MATLAB 中的矢量化简介 - 有什么好的教程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 10:02