Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
Announcements
FPGA community forums and blogs on community.intel.com are migrating to the new Altera Community and are read-only. For urgent support needs during this transition, please visit the FPGA Design Resources page or contact an Altera Authorized Distributor.
29280 Discussions

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

Peter_F_5
Beginner
2,169 Views

 

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
andrew_4619
Honored Contributor III
2,169 Views

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
jimdempseyatthecove
Honored Contributor III
2,169 Views

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
Reply