如何在没有for循环的情况下在matlab中进行计算 [英] How to calculate this in matlab without for loop

查看:207
本文介绍了如何在没有for循环的情况下在matlab中进行计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于matlab在执行for循环时很慢,所以我通常会避免for循环所有的代码,并把它们转换成矩阵计算,这样会很快。但这里有一个问题,我找不到一个聪明的办法:

我有焦虑矩阵

 a $ a 


$ b >这里a1,a2,a3 .... an是矩阵的列。

另一个nxn矩阵

<












$ b $ $ b 同样b1,b2,b3 ...也是B的列。

还有焦虑矩阵M

我想计算nxn矩阵

  C = [c1,c2,c3,..., (M + diag(ai))* ci = bi,那么b 
$ b。



  ci =(M + diag(ai))\ bi。 

我知道一个没有for循环的方法是:

C:(=)(blkdiag(M)+ diag(A(:)))\ B(:)。

但是这会做太多计算。



任何智能解决方案?你可以假设在计算中没有奇点问题。

解决方案

语句for循环在Matlab中很慢不再是一般真正的Matlab ... euhm,R2008a? (有人请填我这个:)

无论如何,试试这个:

  clc 
清除全部

M = rand(50);
a = rand(50);
b = rand(50);

%简单循环方法
tic
c = zeros(size(b)); (b,2)
c(:,ii)=(M + diag(a(:,ii)))\ b(:,ii);
end
toc

%不是那么简单的矢量化方法
tic
MM = repmat({M},50,1);
c2 =(blkdiag(MM {:})+ diag(a(:)))\b(:);
toc

norm(c(:) - c2(:))

结果:

 已用时间为0.011226秒。 %循环
已用时间为1.049130秒。 %no-loop
ans =
5.091221148787843e-10%结果确实是相等的

可能有更好的方法来向量化操作,但是我怀疑它比JIT的循环版本要快得多。

有些问题不适合矢量化。我认为这是一个。

Since matlab is slow when executing for loop, I usually avoid for loop for all my codes, and turn those into matrix calculation, which would be way fast. But here is a problem I can not find a smart way:

I have a n x n matrix

A=[a1,a2,a3,...,an], 

here a1,a2,a3....an are columns of the matrix.

Another n x n matrix

B=[b1,b2,b3,...,bn], 

similarly b1,b2,b3... are also columns of B.

And also a n x n matrix M.

I want to calculate the n x n matrix

C=[c1,c2,c3,...,cn], 

thus (M+diag(ai))*ci = bi.

namely

ci = (M+diag(ai))\bi.

I know one way without for loop is:

C(:)=( blkdiag(M)+diag(A(:)) )\B(:).

But this will do too much calculation than needed.

Any smart solutions? you can assume there is no singularity problem in the calculation.

解决方案

The statement "for loops are slow in Matlab" is no longer generally true since Matlab...euhm, R2008a? (someone please fill me in on this :)

Anyway, try this:

clc
clear all

M = rand(50);
a = rand(50);
b = rand(50);

% simple loop approach
tic
c = zeros(size(b));
for ii = 1:size(b,2)
    c(:,ii) = ( M+diag(a(:,ii)) ) \ b(:,ii);
end
toc

% not-so-simple vectorized approach
tic
MM = repmat({M}, 50,1);
c2 = (blkdiag(MM{:})+diag(a(:)))\b(:);
toc

norm(c(:)-c2(:))

Results:

Elapsed time is 0.011226 seconds.  % loop
Elapsed time is 1.049130 seconds.  % no-loop
ans =
     5.091221148787843e-10         % results are indeed "equal"

There might be a better way to vectorize the operation, but I doubt it will be much faster than the JIT'ed loop version.

Some problems are just not suited for vectorization. I think this is one.

这篇关于如何在没有for循环的情况下在matlab中进行计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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