[英]Operate on all rows of a matrix without loop, octave
Suppose I have a matrix A and I want to obtain the following: 假设我有一个矩阵A,我想获得以下值:
for i=1:m
A(i,:) = something which depends on i;
endfor
Is there a way to obtain that without the loop? 有没有办法在没有循环的情况下获得它?
Added: Ok, I've understood I have to be more specific. 补充:好的,我知道我必须更加具体。
I have two matrices B
and C
(all the matrices we are considering have m
rows). 我有两个矩阵
B
和C
(我们正在考虑的所有矩阵都有m
行)。
I want to record in the i
-th row of A
the product of the polynomials written in the i
-th rows of B
and C
(so using the loop I would call the conv function). 我想在
A
的第i
行中记录写在B
和C
第i
行中的多项式的乘积(因此使用循环,我将调用conv函数)。 Any ideas? 有任何想法吗?
That is a very very general question, and not possible to answer with more details. 这是一个非常非常笼统的问题,无法回答更多细节。 Mainly on what
i
will be involved with. 主要涉及
i
将参与的工作。 Suppose the following 假设以下
for i = 1:m
A(i,:) += i;
endfor
It could be written with the much more efficient: 它可以用效率更高的方式编写:
A .+ (1:m)'
Just compare: 只是比较一下:
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)')
. 如果您的八度音阶版本非常旧,则可以执行
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. 但是,如果表达式右侧的
i
将用于索引其他变量,则解决方案将有所不同。 Maybe, the solution is cumsum
, or some other of cumfoo
function. 也许解决方案是
cumsum
或其他cumfoo
函数。
Your question is basically, "how do I vectorize code?", which is a really large subject, without telling us what you're trying to vectorize. 您的问题基本上是“如何对代码进行向量化?”,这是一个非常大的主题,没有告诉我们您要对向量化的内容。
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. 我认为没有for循环就不可能做到这一点,因为
conv
只接受向量输入,但是我可能错了。 I can't see a way of using either bsxfun
or arrayfun
in conjunction with conv
and matrix inputs. 我看不到将
bsxfun
或arrayfun
与conv
和matrix输入结合使用的方法。 I might be wrong though... I stand to be corrected. 我可能是错的...我会得到纠正。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.