Reputation: 348
I'm trying to construct an array that has, as elements, the SUM of the dot product of two vectors. Like so:
I used the following code, but I don't think it's right, so plese help.
do j = 0, m
do i = 1, N
temp(i) = (x(i)**j)*y(i)
b(j) = vectorsum(temp)
end do
end do
Where x is the vector Xi, y is the function f, j is the power m, temp is a temporary vector containing the operation on the current element,
Thank you.
Upvotes: 3
Views: 465
Reputation: 8536
You should use the intrinsic function sum
, that takes an array and reduce it by addition. Intrinsic are pretty optimized, so they are usually recommended when they may apply.
There are plenty of syntactic ways to accomplish it, and many of them with the intrinsic sum
. Here there are some of them (I am using the same notation as your image, not from your sample):
implicit none
integer, parameter :: m=5,n=3
integer :: i, j, x(0:n), f(0:n), b(0:m)
x = [0,1,2,3]
f = [0,1,2,3]
! using array implied-do construction inside sum
do i = 0,m
b(i) = sum([(x(j)**i * f(j), j=0,n)])
end do
print *, b ! output: 6 14 36 98 276 794
! using Fortran's whole array operations
do i = 0,m
b(i) = sum(x**i * f)
end do
print *, b ! output: 6 14 36 98 276 794
! using implied-do constructor outside, without explicit do
b = [(sum(x**i * f), i=0,m)]
print *, b ! output: 6 14 36 98 276 794
end
Upvotes: 3
Reputation: 5559
In Fortran, you can raise a vector/matrix to a scalar power or another vector/matrix having the same size, this is done element-wise. So, you don't actually need the inner loop or the temporary temp
to store the partial product x**j * y
. In the example below, you will get an m+1
vector, b
, whose jth
element is the sum of elements x^j * y
.
program test_sumvec
implicit none
integer, parameter :: m = 10, N = 10
real :: x(0:N), y(0:N), b(0:m)
integer :: j
x = 2
y = 1
do j = 0, m
b(j) = sum(x**j * y)
end do
print *, b(0:4)
end program test_sumvec
Upvotes: 2