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?
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.
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.
The takeaway: matrices/vectors can only be added if they have the same dimensions.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With