You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python转MATLAB代码问题:states2_M无法匹配states2_P

Python转MATLAB代码不匹配问题

我有如下Python代码:

import numpy as np
from scipy.io import savemat
states = np.array([[1,2,3,4,4,4,4,4],[5,6,7,8,8,8,8,8],[9,10,11,12,12,12,12,12],[2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2],[2,2,2,2,2,2,2,2]])
states2_P = states.copy()
for j in range(2,np.shape(states2)[0]-2):
    if (np.mod(j,2)==0):
        # print(states.shape)
        states2_P[j,:] = (states[j-1,:]*states[j-2,:]).copy()
savemat('states.mat',{"foo": states})

我尝试将其改写为MATLAB代码:

close all;
clear all;
clc;
states = double(cell2mat(struct2cell(load('states.mat'))));
states2_M = states(:,:);
for i=3:size(X_aug,1)-1
    if mod(i,2)==0
        states2_M(i,:) = states(i-1,:).*states(i-2,:); 
    end 
end

我希望states2_M能与states2_P匹配,请问我的MATLAB代码存在什么错误?


错误点及修正方案

  • 未定义变量X_aug:循环中引用了未定义的X_aug,需替换为目标数组states。
  • 循环范围不匹配:
    Python使用0-based索引,循环覆盖第2到第7行(range(2, 10-2),左闭右开);MATLAB是1-based索引,对应行号应为3到8,因此循环范围需改为i=3:size(states,1)-2。
  • 奇偶判断逻辑错误:
    Python中判断0-based索引j为偶数时执行操作,对应MATLAB的1-based索引i = j+1,因此条件应改为mod(i,2)==1(判断i为奇数),而非mod(i,2)==0。
  • 冗余的文件加载操作:
    Python保存的变量名为foo,MATLAB加载时直接通过states = load('states.mat').foo;即可获取数组,无需额外的cell2mat、struct2cell和double转换。

修正后的MATLAB代码

close all;
clear all;
clc;
% 正确加载mat文件中的目标变量
states = load('states.mat').foo;
states2_M = states; % 直接复制数组,等价于Python的copy()
% 匹配Python的循环范围与逻辑
for i = 3:size(states,1)-2
    if mod(i,2) == 1
        states2_M(i,:) = states(i-1,:) .* states(i-2,:);
    end
end

内容的提问来源于stack exchange,提问作者Jonathan Frutschy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 22:22:49