在matlab和python中创建类似的矩阵对象

问题描述 投票:0回答:1

出于比较目的,我想创建一个在 matlab 和 python (numpy) 中具有相同形状和索引属性的对象。 假设在 matlab 端该对象是:

arr_matlab = cat(4, ...
    cat(3, ...
        [  1,   2;
           3,   4;
           5,   6], ...
        [  7,   8;
           9,  10;
          11,  12], ...
        [ 13,  14;
          15,  16;
          17,  18], ...
        [ 20,  21;
          22,  23;
          24,  25]), ...
    cat(3, ...
        [ 26,  27;
          28,  29;
          30,  31], ...
        [ 32,  33;
          34,  35;
          36,  37], ...
        [ 38,  39;
          40,  41;
          42,  43], ...
        [ 44,  45;
          46,  47;
          48,  49]), ...
    cat(3, ...
        [ 50,  51;
          52,  53;
          54,  55], ...
        [ 56,  57;
          58,  59;
          60,  61], ...
        [ 62,  63;
          64,  65;
          66,  67], ...
        [ 68,  69;
          70,  71;
          72,  73]), ...
    cat(3, ...
        [ 74,  75;
          76,  77;
          78,  79], ...
        [ 80,  81;
          82,  83;
          84,  85], ...
        [ 86,  87;
          88,  89;
          90,  91], ...
        [ 92,  93;
          94,  95;
          96,  97]), ...
    cat(3, ...
        [ 98,  99;
         100, 101;
         102, 103], ...
        [104, 105;
         106, 107;
         108, 109], ...
        [110, 111;
         112, 113;
         114, 115], ...
        [116, 117;
         118, 119;
         120, 121]));
K>> size(arr_matlab)

ans =

     3     2     4     5

K>> arr_matlab(1, 2, 1 ,1)

ans =

     2

size(arr_matlab) 应与 arr_python.shape 相同,并且索引应给出相同的结果(例如 arr_python[0,1,0,0] 和 arr_matlab(1,2,1,1) 的结果相同)。 目前我还做不到。

data = np.array([
     ...:     1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25,
     ...:     26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
     ...:     50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
     ...:     74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
     ...:     98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121
     ...: ])
     ...: 
     ...: # Reshape to 3x2x4x5
     ...: arr_python = data.reshape((3, 2, 4, 5), order='F')
In [138]: arr_python.shape
Out[138]: (3, 2, 4, 5)
 arr_python[0,1,0,0]
Out[143]: 4
python numpy matlab
1个回答
0
投票

这就是您想要在 Python 和 MatLab 中实现的目标:

MatLab

arr_matlab = reshape(1:120, [3, 2, 4, 5]);
L = size(arr_matlab);
disp(L);
disp(arr_matlab(1, 2, 1, 1));

打印

3   2   4   5

4

Python

import numpy as np

data = np.array(list(range(1, 120 + 1)))
arr_python = data.reshape((3, 2, 4, 5), order='F')
print(arr_python.shape)
print(arr_python[0, 1, 0, 0])

打印

(3, 2, 4, 5)
4

请注意,Python 的结束范围不包括在内。

© www.soinside.com 2019 - 2024. All rights reserved.