0

I want to achieve this function in Python like Matlab

in matlab, the code is (B and C are variables in loop)

A = [];
for ii = 1:10
    A = [A, B, C]
end

but in Python, use np.hstack or np.concatenate, the ndarray must have same number of dimensions

and, that is my Python code

for ii in range(10):
    if ii == 0:
        A = np.hstack([B, C])
    else:
        A = np.hstack([A, B, C])

but, i think it a little troublesome and unreadable.

how can i rewrite it?(It's better to use only one line of code)

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
ran tao
  • 21
  • 1
  • What is your desired output? – Kay Apr 09 '20 at 03:03
  • What is your actual input? – Mad Physicist Apr 09 '20 at 03:29
  • Short answer, `np.hstack` once and then `np.tile`. Even in MATLAB, your loop is not a recommended approach. – Mad Physicist Apr 09 '20 at 03:33
  • why close my question?B and C is variable not constant,NOT REPEAT NDARRAY! – ran tao Apr 09 '20 at 03:56
  • We recommend setting `alist=[]`, and doing `alist.append(B)` in the loop. Then do **one** `np.hstack(alist)` at the end. List append is much more efficient because it just adds a reference in-place. Repeated `hstack` is slower because it makes a new array (with full copy) each time. – hpaulj Apr 09 '20 at 04:11
  • The duplicate isn't the best, but you code example does not adequately convey the variability that you want us to use. Like I wrote above, list append is the way to go. – hpaulj Apr 09 '20 at 06:06

0 Answers0