Suppose I have a matrix A and I want to obtain the following:
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).
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). 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. 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)')
.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.