gpt4 book ai didi

python - 从 Matlab 矩阵分配变量值

转载 作者:太空宇宙 更新时间:2023-11-04 03:04:45 24 4
gpt4 key购买 nike

由于我有 numpy 背景,几天前我不得不使用 Matlab 来完成一个新项目。

切换到 Matlab 非常简单,因为语法在某种程度上与 numpy 的语法相当。但是,有一件事我无法以令人满意的方式“转换”。

在 numpy 中,我可以根据数组的行(或“矩阵”im Matlab 术语)分配变量,如下所示:

import numpy as np

arr = np.array([1, 2, 3])
a, b, c = arr
print(a, b, c)

arr = np.array([[1, 2, 3], [11, 22, 33]])
for row in arr:
a, b, c = row
print(a, b, c)

这看起来很优雅。但是,在不使用索引符号访问矩阵的每个元素的情况下,我没有找到在 Matlab 中执行此操作的等效方法。

是否有一种等效的方法来执行变量赋值,如我在 Matlab 中的 Python 片段的第二部分所示,还是我必须使用显式索引符号?

最佳答案

在 MATLAB 中真正做到这一点的唯一方法是使用 comma-separated list将元胞数组的内容“分配”给多个变量。不利的一面是,它要求您首先使用类似 num2cell 的方式将行(数字数组)转换为元胞数组。 .

% Create an example numeric array
data = [1, 2, 3];

% Convert your data to a cell array
data_as_cell = num2cell(data);

% Use {:} indexing to convert the cell into a comma-separated list
[a, b, c] = data_as_cell{:};

关于python - 从 Matlab 矩阵分配变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39808429/

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