Fortran element by element array multiplication

  • Comp Sci
  • Thread starter Kwetla
  • Start date
  • #1
3
0

Homework Statement



Hello,

I'm having a problem in multiplying two vectors together in a specific way in Fortran. I can do it in Matlab, but can't work out how to do it in Fortran.

The problem is that i want to multiply two vectors together, but only each element by it's corresponding element in the other vector. In Matlab you simply use A.*B which works perfectly.



Homework Equations



For example if A = [1 2 3]'

and B = [4 5 6]'

Then A.*B = [4 10 18]



The Attempt at a Solution



Any attempt i make in Fortran tries to multiply all the elements together (usually by dot product etc), but i just want the first element multiplied by the first element, and then the second mulitplied by the second etc.

Sorry about the strange formatting, i tried to crowbar this question into the template...
 
Last edited by a moderator:

Answers and Replies

  • #2
33,744
5,433

Homework Statement



Hello,

I'm having a problem in multiplying two vectors together in a specific way in Fortran. I can do it in Matlab, but can't work out how to do it in Fortran.

The problem is that i want to multiply two vectors together, but only each element by it's corresponding element in the other vector. In Matlab you simply use A.*B which works perfectly.



Homework Equations



For example if A = [1 2 3]'

and B = [4 5 6]'

Then A.*B = [4 10 18]



The Attempt at a Solution



Any attempt i make in Fortran tries to multiply all the elements together (usually by dot product etc), but i just want the first element multiplied by the first element, and then the second mulitplied by the second etc.

Sorry about the strange formatting, i tried to crowbar this question into the template...
Assuming that all variables and the three arrays are declared and that A and B are initialized, this should work.
Code:
N = 3
DO I = 1, N
  C(I) = A(I) * B(I)
END DO
 
  • #3
3
0
Ah yes, that would work. Although i'm surprised there isn't a function for it.

Thanks a lot though!
 
  • #4
1,198
5
Vector times vector can also be a scalar, 32.
 
  • #5
hotvette
Homework Helper
996
5
If you are using at least Fortran 90, I believe the following will work:

C = A*B

or

C(1:N) = A(1:N)*B(1:N)

The 1st version assumes A,B,C have the same dimension. The 2nd version is safer.
 

Related Threads on Fortran element by element array multiplication

  • Last Post
2
Replies
42
Views
4K
  • Last Post
Replies
1
Views
777
  • Last Post
Replies
3
Views
620
  • Last Post
Replies
6
Views
781
Replies
4
Views
2K
  • Last Post
Replies
18
Views
913
Replies
1
Views
563
Replies
13
Views
1K
Replies
7
Views
3K
Top