pythonarraysmatlabmatrix-multiplicationremainder

Augment Array in MATLAB


I have the following code in 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})

I am trying to write the same code in 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

I would like states2_M to match states2_P. What am I doing wrong in my MATLAB code?


Solution

  • In MATLAB, indexing is 1-based, in Python 0-based. You adjusted indices everywhere, it left the condition mod(i,2)==0 in place. This is true in Python for the first array element, and every second element after that. In MATLAB it is true for the second array element, and every second element after that.

    In MATLAB you’d need mod(i,2)==1 to match Python.

    You can actually leave the if statement out, and modify the loop to increase in steps of two: for i=3:2:size(X_aug,1)-1. Your Python code can be adjusted in exactly the same way.