Am 25.03.2015 um 21:09 schrieb Dr.-Ing. Dieter Jurzitza:
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
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
advance,
take care
Dieter,
after vectorization you will have no for-loop anymore. Instead you have
a single assignment, which updates the whole array at once.
> for i=2:numelem
> B(i)=B(i-1)+A(i);
> endfor
Lets solve this step by step. If you did B=B+A, this would compute the
sum of B and A element-wise and be equivalent to:
for i=1:numelem
B(i)=B(i)+A(i);
endfor
You do not want the sum of n elements, but the sum of n-1 elements. You
can achieve this by working on subsets of the arrays with range indices:
B(2:end) = B(2:end) + A(2:end);
… which is equivalent to …
for i=2:numelem
B(i)=B(i)+A(i);
endfor
Last, you want to shift indices of the first addend, which is also
possible:
B(2:end) = B((2:end) - 1) + A(2:end);
or alternatively
B(2:end) = B(1:end - 1) + A(2:end);
and not forget: B(1)=A(1);