I'm trying to translate a matlab code, and I'm strugeling to translate this part of the code:
[data;SS(ind-1:-1:ind-9)']
In the following context:
SS = 1:288
year = 1:288
data = [];
for ind = 10:length(year)
data = [data;SS(ind-1:-1:ind-9)'];
end
What I've done at the moment is:
SS = range(1,288);
year = range(1,288);
data = [];
for ind in range(10,length(year)):
data.append(######) # code to translate
EDIT: (Output Correction, wrong parameters)
1:288 is in python list(range(1,289)) or if you use numpy numpy.arange(1,289).
For index access you have to know, that matlab starts with 1, python with 0, so SS(ind-1:-1:ind-9) becomes SS[ind-2:ind-11:-1]
SS = list(range(1,289))
data = []
for ind in range(9,len(SS)):
data.append(SS[ind-9:ind][::-1])
or using numpy:
data = numpy.arange(9,0,-1)[None,:] + numpy.arange(279)[:, None]
Related
Hii guys I am stuck in this bad situation I have to place multiple lists in excel at specific cell co-ordinates and cannot find any solution anywhere
Current implementation :
#xl_func("string key: object", macro=True)
def calc(key) -> object:
result = [[1, 2], [3, 4]]
from pyxll import xl_app, XLCell
caller = xlfCaller()
address = caller.address
xl = xl_app()
xl_range = xl.Range(address)
one_below = xl_range.GetOffset(RowOffset=1, ColumnOffset=0)
XLCell.from_range(one_below)
cell = XLCell.from_range(one_below)
cell.options(type="var", auto_resize=True).value = result
return "123"
This code works perfectly for a single set of data. but now I want to add multiple such datasets on a specific cell co-ordinates . If possible something like follow :
#xl_func("string key: object", macro=True)
def calc(key) -> object:
result = [[1, 2], [3, 4]]
from pyxll import xl_app, XLCell
caller = xlfCaller()
address = caller.address
xl = xl_app()
xl_range = xl.Range(address)
one_below = xl_range.GetOffset(RowOffset=1, ColumnOffset=0)
XLCell.from_range(one_below)
cell = XLCell.from_range(one_below)
#This need to go between A1:A2 to B1:B2
cell.options(type="var", auto_resize=True).value = result
#This need to go between D1:D2 to E1:E2
cell.options(type="var", auto_resize=True).value = result2
#This need to go between F1:F2 to G1:G2
cell.options(type="var", auto_resize=True).value = result3
return "123"
Env:
Python 3.8.6 32 bit
Pyxll 5.0.5 32 bit
You can pass XLCell.from_range either a COM Range object or an address as a string.
c = XLCell.from_range("A1")
c.options(auto_resize=True).value = x
Additionally, you can get a COM Range from an address using Application.Range, for example:
xl = xl_app()
r = xl.Range("A1")
r.Value = x
# or using XLCell
c = XLCell.from_range(r)
c.options(auto_resize=True).value = x
If you need to you can also include the workbook and sheet in the address, eg "[Book1]Sheet1!A1".
Please see https://www.pyxll.com/docs/api/classes.html#pyxll.XLCell.from_range for details.
This FAQ article should also help https://support.pyxll.com/hc/en-gb/articles/360044507453-Writing-arrays-back-to-Excel
Halo, im sabil and newbie using python
First of all, i want to multiplle array with index:
[90,20] with [20,7]
My mentor ask me to not using anything library like (dot,add,etc) but using array
Here is my codefor transpose() :
def nilaiWeightTranspose():
nilaiWTranspose = jumlahBobot
x,y = jumlahBobot.shape
hasil = np.zeros((y,x))
for i in range(y):
for j in range(x):
hasil[i,j] = jumlahBobot.iloc[j,i]
hasilTranspose = pd.DataFrame(data = hasil[0:,0:])
return hasilTranspose
and output :
and here is my code for datanormalisasi():
def minmaxnormalization_latih(dropdata):
minperfeature = []
maxperfeature = []
datanormalisasilatih = datalatih
for i in range(len(dropdata.columns)):
minperfeature.append(min(dropdata[dropdata.columns[i]]))
maxperfeature.append(max(dropdata[dropdata.columns[i]]))
for i in range(len(datalatih.index)):
for j in range(len(datalatih.columns)):
datanormalisasilatih.loc[i, datalatih.columns[j]] = (datanormalisasilatih.loc[i, datalatih.columns[j]] - minperfeature[j]) / (maxperfeature[j] - minperfeature[j])
return datanormalisasilatih
and here is my code if i using library(dot) and succesful :
def nilaiHinit():
hitung_hInit = pd.DataFrame(datanormalisasilatih.values.dot(hasilTranspose.values), columns=jumlahBias.columns)
hitung_hInit_bias = hitung_hInit
the problem is idk how to multiple array without (dot) and i want to multiple array without (dot) or anything, can anyone know how to solve it?
thank you ^^
I am given a frequency range start,end and an integer n:1<=n<=5. The task is to print all 5 linear-spaced mid points in a certain format (for other tools downstream to process it further .. this part is not imp here)
In case n is lesser than 5 the last frequency variables should be defaulted to 0 in the print. I have a working code given below.. I wanted to get more "pythonic" refactoring. Parts of the snippet that I particularly dislike:
No inherent support for dynamic unpacking of list into lesser no of variables. I have used a solution from here - which is over 2 yrs old so looking for a fresh perspective
I don't like having to convert np array to list .. Can np be bye-passed altogether .. is there a standard library range/linspace equivalent?
Code snippet:-
import sys
import numpy as np
max = 5
n=int(sys.argv[1])
if n>max:
print("No of frequency larger than "+ str(max) + " ..resetting")
n=max
if n<1:
print("No of frequency less than 1 resetting to 1")
n=1
fr1=0
fr2=0
fr3=0
fr4=0
fr5=0
start = 5060000
end = 6165000
range = end-start
inc = range/(n+1)
ret_list = np.arange(start+inc,end,inc).tolist()[:n]
ret_list = ret_list + [0]*(max-n)
fr1,fr2,fr3,fr4,fr5 = ret_list
print(".fr1.",fr1, sep = '')
print(".fr2.",fr2, sep = '')
print(".fr3.",fr3, sep = '')
print(".fr4.",fr4, sep = '')
print(".fr5.",fr5, sep = '')
I need to convert a piece of MATLAB code to Python and I'm bad at both. The code in MATLAB uses fft and fftshift. I tried to use NumPy in Python. The code runs but when I compare the outcome they are not matching. I appreciate your help.
Here is the MATLAB code:
h(1,1:Modes_number) = -1i*S;
hfft = fft(h);
hft0 = fftshift(hfft);
and here is the Python code which I wrote:
h = np.zeros((1,self.cfg.Modes_number+1),dtype=complex)
for i in range(0, self.cfg.Modes_number+1):
h[0,i] = -1j*S;
hfft = np.fft.fft(h)
hft0 = np.fft.fftshift(hfft)
Here is the values for S and Modes_number:
S = 12.5022214424;
Modes_number = 200;
Here is also an example of the results I get in MATLAB and Python:
MATLAB:
hfft(1,1)
ans =
1.1857e-13 - 2.5129e+03i
Python:
hfft[0]
0. -2.52544873e+03j
Cheers.
The error in your Python code is that you define h to be of size Modes_number+1, which is one more than the size in the MATLAB code. The first value in hfft is the sum of all input values. In MATLAB this is -1j*S*200 = -2500.4j, and in your Python code this is -1j*S*201 = -2512.9j. These are the values that you are seeing.
This bit of Python code produces the same as your bit of MATLAB code, up to numerical precision (I see some values like -1.68388521e-15 +6.55829989e-15j in Python, which are forced to 0 by MATLAB's algorithms). I am creating h as a one-dimensional vector, rather than a 2D array with one dimension of size 1.
import numpy as np
S = 12.5022214424
Modes_number = 200
h = np.zeros(Modes_number,dtype=complex)
for i in range(0,Modes_number):
h[i] = -1j*S;
hfft = np.fft.fft(h)
hft0 = np.fft.fftshift(hfft)
Python:
>>> hfft[0]
-2500.4442884800001j
MATLAB:
>> hfft(1)
ans =
0.000000000000000e+00 - 2.500444288480000e+03i`
I'm trying to proceed some simple calculation in NumPy.
But it suddenly gives the results different with MATLAB calculations.
Here is the MATLAB example:
load temp; % here are the source matrices located
resp = ang_stv' * tmp;
respC = resp.'; % this is our variable to compare with Python
cd(fileparts(mfilename('fullpath')));
save('arythm_test.mat');
And here I try to calculate the same in Python:
dump_data = sp.io.loadmat("arythm_test.mat")
tmp = dump_data["tmp"]
ang_stv = dump_data["ang_stv"]
ref_resp = dump_data["respC"]
our_resp = np.dot(ang_stv.swapaxes(0, 1), tmp).swapaxes(0, 1)
np.testing.assert_allclose(our_resp, ref_resp)
Cannot you tell me, what am I doing wrong? And how to cope with it?
P.S. Here are temp.mat and arythm_test.mat
The answer was simple: the .' operator in MATLAB means simple transpose, and ' operator means transpose with complex conjugation. Oy vey...
tmp = dump_data["tmp"]
ang_stv = dump_data["ang_stv"]
print "tmp.shape", tmp.shape
print "ang_stv.shape", ang_stv.shape
ref_resp = dump_data["respC"]
our_resp = np.dot(np.conj(ang_stv.swapaxes(0, 1)), tmp).swapaxes(0, 1)