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
3
  • 2
    Possible duplicate of Find length of 2D array Python Commented Jun 15, 2018 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 dedicated to people moving from Matlab. Note in this documentation, there is a table of equivalent operations including size :) Commented Jun 15, 2018 at 19:24
  • Thank you for the tip! I will look into that! Commented Jun 15, 2018 at 20:17

3 Answers 3

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')
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your help! p is a parameter of the function from which this part of the code came from.
If information on p is needed, I have posted the rest of the code.
Your additional code still does not enlighten us as to what p is, however it does not matter for the context of your question.
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")

Comments

1
number_of_rows = Y.__len__()
number_of_cols = Y[0].__len__()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.