0

I am working on matlab conversion code to python.
I do not understand these 2 lines of code.

d1 = s(1:3,2) - s(1:3,1);
d2 = s(1:3,end) - s(1:3,end-1);

what these 2 lines are doing? can anyone explain me?
and how will i convert this in python?

sam
  • 18,509
  • 24
  • 83
  • 116

3 Answers3

3

In Matlab:

% Matlab
s = [1,2,3,4,5; ...
    6,7,8,9,10; ...
    11,12,13,14,15];
d1 = s(1:3,2) - s(1:3,1);
d2 = s(1:3,end) - s(1:3,end-1);

disp('--s--')
disp(s)
disp('--d1--')
disp(d1)
disp('--d2--')
disp(d2)

disp('--s(1:3,2)--')
disp(s(1:3,2))
disp('--s(1:3,1)--')
disp(s(1:3,1))

disp('--s(1:3,end)--')
disp(s(1:3,end))
disp('--s(1:3,end-1)--')
disp(s(1:3,end-1))

can be translated to Python as:

# Python
import numpy as np

s = np.asarray([ \
    1,2,3,4,5, \
    6,7,8,9,10, \
    11,12,13,14,15]).reshape(3,-1);
d1 = s[0:3,1] - s[0:3,0];
d2 = s[0:3,-1] - s[:3,-2];

print '--s--'
print s
print '--d1--'
print d1
print '--d2--'
print d2

print '--s[0:3,1]--'
print s[0:3,1]
print '--s[0:3,0]--'
print s[0:3,0]

print '--s[0:3,-1]--'
print s[0:3,-1]
print '--s[0:3,-2]--'
print s[0:3,-2]

Results of Matlab:

--s--
    1    2    3    4    5
    6    7    8    9   10
   11   12   13   14   15
--d1--
   1
   1
   1
--d2--
   1
   1
   1
--s(1:3,2)--
    2
    7
   12
--s(1:3,1)--
    1
    6
   11
--s(1:3,end)--
    5
   10
   15
--s(1:3,end-1)--
    4
    9
   14

vs of Python:

--s--
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]]
--d1--
[1 1 1]
--d2--
[1 1 1]
--s[0:3,1]--
[ 2  7 12]
--s[0:3,0]--
[ 1  6 11]
--s[0:3,-1]--
[ 5 10 15]
--s[0:3,-2]--
[ 4  9 14]

They match.

Evaluate Matlab code online /here/ and Python code /here/, /here/ and with packages /here/.

Developer
  • 8,258
  • 8
  • 49
  • 58
  • I'd probably prefer `np.array([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]])` there - note that you don't need `\ ` to continue a line within `{[(` – Eric Jan 06 '14 at 11:43
  • @Eric Your point is totally correct. We just tried to keep `Python` translation similar to `Matlab` code as much as possible. – Developer Jan 06 '14 at 12:09
  • Also, you really shouldn't use semicolons in python – Eric Jan 06 '14 at 12:20
2

s is a matrix. s(1:3,2) creates a vector from rows 1 to 3 and column 2. s(1:3,1) creates a vector from rows 1 to 3 and column 1. d1 is then another vector being the element by element difference

end is special syntax for the last row or column. end-1 is the penultimate row/column

David Waterworth
  • 2,214
  • 1
  • 21
  • 41
1

d1: the difference between 2nd column and 1st column of the first 3 rows of s

d2: the difference between last column and the one before last column of the first 3 rows of s

You can test it online

lennon310
  • 12,503
  • 11
  • 43
  • 61