1

I am trying to translate some code from MATLAB to Python. I have been stumped on this part of the MATLAB code:

[L,N] = size(Y);
if (L<p)
    error('Insufficient number of columns in y');
end

I understand that [L,N] = size(Y) returns the number of rows and columns when Y is a matrix. However I have limited experience with Python and thus cannot understand how to do the same with Python. This also is part of the reason I do not understand how the MATLAB logic with in the loop can be also fulfilled in Python.

Thank you in advance!

Also, in case the rest of the code is also needed. Here it is.

function [M,Up,my,sing_values] = mvsa(Y,p,varargin)

if (nargin-length(varargin)) ~= 2
    error('Wrong number of required parameters');
end

% data set size
[L,N] = size(Y)

if (L<p)
    error('Insufficient number of columns in y');
end
A.Torres
  • 413
  • 1
  • 6
  • 16
  • 2
    Possible duplicate of [Find length of 2D array Python](https://stackoverflow.com/questions/10713004/find-length-of-2d-array-python) – Sardar Usama Jun 15 '18 at 19:14
  • If you are changing over to Python from Matlab - I suggest you use numpy. There's even a section of [the numpy docs](https://docs.scipy.org/doc/numpy-1.14.0/user/numpy-for-matlab-users.html) dedicated to people moving from Matlab. Note in this documentation, there is a table of equivalent operations including `size` :) – LinkBerest Jun 15 '18 at 19:24
  • Thank you for the tip! I will look into that! – A.Torres Jun 15 '18 at 20:17

3 Answers3

4

I am still unclear as to what p is from your post, however the excerpt below effectively performs the same task as your MATLAB code in Python. Using numpy, you can represent a matrix as an array of arrays and then call .shape to return the number of rows and columns, respectively.

import numpy as np

p = 2
Y = np.matrix([[1, 1, 1, 1],[2, 2, 2, 2],[3, 3, 3, 3]])

L, N = Y.shape
if L < p:
    print('Insufficient number of columns in y')
rahlf23
  • 8,869
  • 4
  • 24
  • 54
  • Thank you for your help! p is a parameter of the function from which this part of the code came from. – A.Torres Jun 15 '18 at 20:16
  • If information on p is needed, I have posted the rest of the code. – A.Torres Jun 15 '18 at 20:35
  • Your additional code still does not enlighten us as to what `p` is, however it does not matter for the context of your question. – rahlf23 Jun 15 '18 at 20:39
2

Non-numpy

 data = ([[1, 2], [3, 4], [5, 6]])    

 L, N = len(data), len(data[0])

 p = 2

 if L < p:
     raise ValueError("Insufficient number of columns in y")
C.Nivs
  • 12,353
  • 2
  • 19
  • 44
1
number_of_rows = Y.__len__()
number_of_cols = Y[0].__len__()