Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting or adding vectors in a matrix

Tags:

arrays

fortran

I am trying to subtract vectors of a matrix. In other words suppose that I have matrix A with elements

x1    x2    x3    x4
y1    y2    y3    y4
z1    z2    z3    z4

I want to be able to subtract vectors

x1  
y1
z1

and

x2
y2
z2

How would I be able to do this? I tried doing

implict none
real, dimension(3,4) :: A
real,dimension(3) :: vector
vector(1)=A(1,1)-A(1,2)
vector(2)=A(2,1)-A(2,2)
vector(3)=A(3,1)-A(3,2)

However, this is rather crude. Also, this method would be impractical if I need to compute several sums or residues, especially when the matrix is very large. I want to be able to do it more elegantly.

Is there a way to specify a vector inside a matrix? Or is there a roundabout way to do this?

like image 677
CoffeeIsLife Avatar asked Mar 26 '16 05:03

CoffeeIsLife


People also ask

Can you subtract a vector from a matrix?

As usual, subtraction is just addition of the negative, so if you know how to add matrices and vectors, you already know how to subtract them. For matrices or vectors to be added, they must have the same dimensions. Matrices and vectors are added or subtraced element by corresponding element.

What is the rule for matrix addition and subtraction?

We can only add or subtract matrices if their dimensions are the same. To add matrices, we simply add the corresponding matrix elements together. To subtract matrices, we simply subtract the corresponding matrix elements together.

Can a matrix and vector be added?

The takeaway: matrices/vectors can only be added if they have the same dimensions.


1 Answers

You can specify array slices by [start]:[end][:stride] (Fortran 2008 Standard, Cl. 6.5.3 "Array elements and array sections": R621). To select all elements along a specified dimension, choose e.g., A(:,1). Your difference then reads:

implicit none
real, dimension(3,4) :: A
real,dimension(3) :: vector
vector(:)=A(:,1)-A(:,2)

or even

vector=A(:,1)-A(:,2)
like image 132
Alexander Vogt Avatar answered Oct 19 '22 14:10

Alexander Vogt