0

假设我有一个矩阵 A 并且我想获得以下内容:

for i=1:m
  A(i,:) = something which depends on i;
endfor

有没有办法在没有循环的情况下获得它?

补充:好的,我知道我必须更具体。
我有两个矩阵BC(我们正在考虑的所有矩阵都有m行)。
我想记录在和的第i-行中A写入的多项式乘积的i-第-行(因此使用循环我将调用conv函数)。有任何想法吗?BC

4

2 回答 2

0

这是一个非常笼统的问题,无法回答更多细节。主要i是涉及到什么。假设以下

for i = 1:m
  A(i,:) += i;
endfor

它可以用更有效的方式编写:

A .+ (1:m)'

只是比较:

octave> n = 1000;
octave> A = B = rand (n);
octave> tic; for i = 1:n, B(i,:) += i; endfor; toc
Elapsed time is 0.051 seconds.
octave> tic; C = A.+ (1:n)'; toc
Elapsed time is 0.01 seconds.
octave> isequal (C, B)
ans =  1

If you have a very old version of octave, you can instead do bsxfun (@plus, A, (i:m)').

However, if i on the right side of the expression will be used for indexing some other variable, then solution would be different. Maybe, the solution is cumsum, or some other of cumfoo function.

Your question is basically, "how do I vectorize code?", which is a really large subject, without telling us what you're trying to vectorize.

于 2013-05-10T12:47:57.210 回答
0

I don't think it's possible to do this without a for loop as conv only accepts vector inputs, but I might be wrong. I can't see a way of using either bsxfun or arrayfun in conjunction with conv and matrix inputs. I might be wrong though... I stand to be corrected.

于 2013-05-10T15:12:11.477 回答