-1

I have a python code like this

import numpy as np
a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
a=np.array(a)
b = np.zeros(shape = (3,5))
x = 0;
for i in range(0, 3):
    for j in range (0, 5):
        b[i,j] = a[x];
        x= x+1
    print(b[i,:])

The output of this code is as follows:

[1. 2. 3. 4. 5.]
[ 6.  7.  8.  9. 10.]
[11. 12. 13. 14. 15.]

What is the equivalent MatLab code for this python code? I would be grateful if anybody help me with this problem.

Virtuall.Kingg
  • 166
  • 2
  • 12
  • Not matlab code, but if you were to stick with python, numpy has a lot of functionality for working with arrays like this: `np.arange(1, 16).reshape((3, 5))` should give the required output in python. – Swier Jul 02 '20 at 11:19

1 Answers1

2
a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
% a = 1:15 or a = linspace(1,15,1) as alternative
b = zeros(3,5);
x = 1; % Matlab starts at 1, not 0

for ii=1:3
    for jj=1:5
        b(ii,jj) = a(x);
        x = x+1;
    end
end
b % if you want output

I think this would be a 1:1 translation of your code, even though it is not that beautiful

Easier:

b = reshape(a, [5,3])'

I think. reshapes a and then transposes to fit your output

Wyall
  • 36
  • 3
  • 1
    Your vectorised manner doesn't do what you expect it does, check the output. You need to transpose elsewhere. Second note on MATLAB habits: `'` denotes **complex transpose** rather than normal transpose. Use `.'` for the [matrix transpose](https://stackoverflow.com/a/25150319/5211833). – Adriaan Jul 02 '20 at 11:38
  • @Adriaan Thanks for the comment. For me the output looks good? It's a 3x5 with values like requested. 1->5, 6->1 below and 11->15 at the bottom – Wyall Jul 02 '20 at 13:22
  • Apologies, I was put off by a comment of the OP on a now-deleted answer which has this exact reshape solution. They mentioned that they obtained a transposed output, which indeed is not the case. Your output is correct. – Adriaan Jul 02 '20 at 13:48