gpt4 book ai didi

python - Matlab 到 Python 矩阵代码

转载 作者:太空宇宙 更新时间:2023-11-04 07:29:36 25 4
gpt4 key购买 nike

我正在尝试将一些代码从 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')

关于python - Matlab 到 Python 矩阵代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50881474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com