Skip to main content
 首页 » 编程设计

python之Matlab 到 Python 矩阵代码

2025年05月04日17小虾米

我正在尝试将一些代码从 MATLAB 转换为 Python。我一直对这部分 MATLAB 代码感到困惑:

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

我知道当 Y 是矩阵时,[L,N] = size(Y) 返回行数和列数。但是我对 Python 的经验有限,因此无法理解如何用 Python 做同样的事情。这也是我不明白循环中的 MATLAB 逻辑如何在 Python 中也能实现的部分原因。

提前致谢!

此外,如果还需要其余代码。这里是。

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 

请您参考如下方法:

我仍然不清楚您的帖子中的 p 是什么,但是下面的摘录有效地执行了与 Python 中的 MATLAB 代码相同的任务。使用 numpy,您可以将矩阵表示为数组的数组,然后调用 .shape 分别返回行数和列数。

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')