Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted
Beginner
12 Views

Subtract a vector from a matrix in fortran (row-wise)

 

Suppose I have a matrix A in fortran which is (n,m), and a vector B which is (1,m). I want to subtract the vector B from all rows of A without using a loop.

As of now I have only been able to do it with a loop:

PROGRAM Subtract
IMPLICIT NONE

REAL, DIMENSION(250,5) :: A
INTEGER, DIMENSION(1,5) :: B
INTEGER :: i

B(1,1) = 1
B(1,2) = 2
B(1,3) = 3
B(1,4) = 4
B(1,5) = 5

CALL RANDOM_NUMBER(A)

do i=1,250
    A(i,:) = A(i,:) - B(1,:)
end do


end program

But this is very inefficient. E.g. in matlab one can do it in one line using the function reptmat. Any suggestion on better way to do this?

 

 

Edit: Just solved using

A = A - spread( B(1,:), 1, 250 )
 
0 Kudos
2 Replies
Highlighted
Valued Contributor II
12 Views

How do you define efficient?

How do you define efficient? Your first example is clear to read and understand the later one-liner  is somewhat more opaque.  As to the computational time for each option that is hard to predict without doing some timing but you will have to make the problem several 1000 times bigger to measure a time difference.

 

0 Kudos
Highlighted
12 Views

This is much like the

This is much like the foolishness of writing a program in one C statement (or LISP expression)... without the regards of the costs in efficiencies.

The one statement above will (may) require the creation of a temporary array, populating it, then performing the array subtraction (which may generate yet another temporary array). The DO loop will not.

Jim Dempsey

0 Kudos