如何在MATLAB代码中将这个For循环向量化? [英] How can I Vectorize this For Loop in MATLAB Code?

查看:794
本文介绍了如何在MATLAB代码中将这个For循环向量化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码需要一段时间才能运行for循环(下面概述)。 CALC是我定义的一个函数;取一个矩阵Y是矩阵; k是一个向量。有没有一种方法,我可以矢量化这个代码,这样我就不用for循环了?任何捐款将不胜感激。

 列= 1:n 
q(:,列)= CALC(D ,Y(:,列),K(列));
end

CALC函数概述如下:

$ b $ p code $函数[x] = CALC(A,y,s)

[m,n] = size(A);

%y是一个m x 1向量
%s是一个整数

r = y;

index_cols = [];
atoms = [];

for i = 1:s

[max_r,lambda_t] = max(abs(r'* A));
index_cols = [index_cols,lambda_t];
atoms = [atoms,A(:,lambda_t)];
x_t = pinv(atoms)* y;
r = y - atoms * x_t;
end
x = zeros(n,1);
x(index_cols)= x_t;
end


解决方案

我将在rayryeng的评论。矢量化意味着把一些基本的操作组合在一起,以便它们可以由一个低级别的例程共同处理。但是你的代码的大部分执行时间是计算 pinv(atoms);其他一切并不昂贵。


  • 如果你的任务是看到几块木头,你可以把它们夹在一起,一次看到它们。这是矢量化。

  • 但是,当你是一名修理几辆汽车的机械师时,这是行不通的。大部分时间将花费在单独的车上。



您可以考虑的事情:


  1. 缓存。你的代码计算矩阵的伪逆矩阵,矩阵总是由同一个矩阵D的列组成。所以可能会碰巧用同样的原子输入多次调用pinv。调查这是否经常足以保证缓存伪装。 这是一个缓存Matlab结果的例子


  2. 并行化,如果你有硬件和软件。

  3. 重新考虑算法...



I have the for loop (outlined below) in my code which takes a while to run. CALC is a function I have defined; Dis a matrix; Y is a matrix; k is a vector. Is there a way I can vectorize this code such that I do away with the for loop? Any contribution will be highly appreciated.

for column = 1:n
    q(:,column) = CALC(D,Y(:,column), k(column));
end

The CALC function is outlined below:

function [x] = CALC(A, y, s)

[m, n] = size(A);

% y is an m x 1 vector
% s is an integer

r = y;

index_cols = [];
atoms      = [];

for i = 1 : s

[max_r, lambda_t] = max(abs(r'*A));
index_cols = [index_cols, lambda_t];
atoms      = [atoms, A(:,lambda_t)];
x_t = pinv(atoms)*y;
r = y - atoms*x_t;
end
x = zeros(n,1);
x(index_cols) = x_t;
end

解决方案

I will expand on rayryeng's comment. Vectorization means grouping some elementary operations together in such a way that they can be jointly handled by a low-level routine. But the bulk of execution time of your code is the computation of pinv(atoms); everything else is not nearly as expensive.

  • If your task is to saw several pieces of wood, you can clamp them together and saw them all at once. That's vectorization.
  • But that does not work when you're a mechanic whose task is to repair several cars. The bulk of your time will have to be spent working on an individual car.

Things you can consider:

  1. Caching. Your code computes pseudoinverses of matrices that are always made of the columns of the same matrix D. So it may happen to call pinv with the same atoms input multiple times. Investigate whether this happens often enough to warrant caching the pseudoinverses. Here's an example of caching Matlab results

  2. Parallelizing, if you have the hardware and software for this.

  3. Rethink the algorithm...

这篇关于如何在MATLAB代码中将这个For循环向量化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆