How would I write the following MatLab code in Python?
9 views (last 30 days)
Show older comments
Sorry for the extremely newb question. I am currently using the Matlab trial to rewrite some Matlab code into Python. I've gotten started with one document and have made good progress. However this line doesn't make sense to me.
f_spec(:,n) = Xs(parameter.coefficientRange(1):parameter.coefficientRange(end)))
This is my best guess in Python:
calc = Xs[self.coefficientRange[0]:int(self.coefficientRange[-1])]
self.f_spec = self.f_spec[:, calc]
But I don't know if that is right. It certainly isn't working anyway!
Please let me know if my understanding is wrong. It seems to me that:
f_spec(:,n)
This is trying to index the vector named 'f_spec' and it's trying to index from the start to the value of 'n'. And the value of 'n' is being resolved from everything after the '=' sign:
Xs(parameter.coefficientRange(1):parameter.coefficientRange(end)))
Do I have that right?
I would really appreciate the help!
3 Comments
tri stan
on 31 Jan 2019
The line
parameter.coefficientRange(1):parameter.coefficientRange(end))
generates vector of consecutive numbers from parameter.coefficientRange(1) to parameter.coefficientRange(end). I assume both these values are integer.
Then
Xs(parameter.coefficientRange(1):parameter.coefficientRange(end)))
takes from array Xs consecutive elements from index parameter.coefficientRange(1) to index
parameter.coefficientRange(end)), so you may think of this line as a vector of length the same as the length of vector
parameter.coefficientRange(1):parameter.coefficientRange(end)
Then, I assume that
f_spec(:,n)
refers to n-th column of two-dimensional array f_spec. You need to make sure that
number of rows of f_spec is the same as length of
Xs(parameter.coefficientRange(1):parameter.coefficientRange(end)))
Anyway, here's the Python code that more or less does what you need (at least I hope so):
import numpy as np
beginingIndex = 3
endIndex = 7
parameter_coefficientRange = np.array([ beginingIndex, endIndex])
# given array
Xs = np.array( [4, 5, 21, 13, 0 , 4, -1, 9 , 13, ] )
n = 2 # number of column you need to fill
temp = Xs[parameter_coefficientRange[0]:parameter_coefficientRange[-1] ]
rowsNo = len(temp)
colsNo = 10 # or whatever number you need
f_spec = np.zeros([rowsNo, colsNo])
f_spec[:,n] = temp
Of course, the code above can be easily shortened, but I'm leaving this part for you.
Helpful tip for those who work simultaneously in Matlab and Python: Always remember that arrays in Matlab are indexed from 1, while in Python - from 0 ;)
Answers (0)
See Also
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!