help-octave
[Top][All Lists]

## Re: Reducing for loop

 From: Markus Bergholz Subject: Re: Reducing for loop Date: Wed, 25 Mar 2015 21:30:10 +0100

On Wed, Mar 25, 2015 at 9:09 PM, Dr.-Ing. Dieter Jurzitza wrote:
Dear listmembers,
I am using a for loop as follows. I have an array, say A, containing numelem
elements.

Now I want to fill array B with elements as follows:

B(1)=A(1)

for i=2:numelem
B(i)=B(i-1)+A(i);
endfor

looks like cumsum(A)

octave:13> A = 1:10;
octave:14> B = zeros(1,10);
octave:15> B(1) = A(1);
octave:16> for n = 2:numel(B), B(n) = B(n-1) + A(n); end
octave:17> all(B == cumsum(A))
ans =                    1

In order to get this vectorized I tried to write something like

B(1)=A(1) # IMHO no way around ...

# apparently does not work ...
for i=2:n
B=A(i)+B(i-1);
endfor

What am I doing wrong here? Apparently using the indexed left - side array on
the right side is causing trouble ... Many thanks for any explanation in
take care

Dieter Jurzitza

--
-----------------------------------------------------------

|
\
/\_/\           |
| ~x~ |/-----\   /
\   /-       \_/
^^__   _        /  _  ____   /
<°°__ \- \_/     |  |/    |  |
||  ||         _| _|    _| _|

if you really want to see the pictures above - use some font
with constant spacing like courier! :-)
-----------------------------------------------------------

_______________________________________________
Help-octave mailing list