Octave_Matlab_Matrix.html#Matrix_Transpose

本文介绍了Matlab和Octave中一些通用的矩阵操作,如创建单位矩阵、零矩阵、全一矩阵,以及数学运算、元素索引、特征值与特征向量、LU分解、元素重新排列等,并提供了实例演示。

在这篇文章中,我会为Matlab和Octave提供一个简单的参考。Octave是一个设计为提供类似于Matlab的免费工具的GNU程序。我认为Octave和Matlab之间可能没有100%的兼容性,但我注意到大多数基本命令是兼容的。我会尝试列出那些可以在Matlab和Octave中通用的命令。这里列出的所有示例代码都是我用Octave尝试的,而不是Matlab。

虽然有很多功能在这里没有解释,但我会尝试列出那些在大多数你可以找到的Matlab样本脚本中最常用的函数。我的目的是为您提供一组基本命令和示例,这样您就可以至少阅读从这里和互联网上获得的大多数样本脚本(例如,互联网),而不会让您感到压倒性。如果您熟悉这些最小功能集,您将对工具有一定的了解,然后您将理解Mathworks或GNU Octave的官方文档,该文档解释了所有函数,但没有太多示例。

我还没有完成“我认为是最小集合”的东西,我希望我能在几周内完成。请保持关注!

矩阵(二维或更高维度数组)

创建矩阵
通用形式
单位矩阵 - eye()
M x N零矩阵 - zeros()
M x N全一矩阵 - ones()
数学运算
加法
减法
逐元素乘法 - element by element
内积乘法 - inner Product
幂 - element by element
幂 - matrix
除法
转置
行列式
逆矩阵
索引元素(引用元素)
matrixname(rowindex,colindex)
matrixname(:,colindex)
matrixname(rowindex,:)
矩阵特定操作
特征值和特征向量
分解
LU分解
重新排列元素
circshift()
resize()

Method 1 :  m = [ value value value ; value value value ;  ...]

 

Ex)

Input

 m = [1 2 3; 4 5 6; 7 8 9]

Output

 m =

   1   2   3

   4   5   6

   7   8   9

 

 

Method 2 :  m = [ vector ; vector ;  ...]

 

Ex)

Input

v1 = [1 2 3];

v2 = [4 5 6];

v3 = [7,8,9];

m = [v1; v2; v3]

Output

 m =

   1   2   3

   4   5   6

   7   8   9

 

 

< Creating an Identity Matrix >

 

Method 1 :  m = eye(M) // M x M identity matrix

 

Ex)

Input

 m = one(3)

Output

 m =

   1   0   0

   0   1   0

   0   0   1

 

 

< Creating M x N Zero Matrix >

 

Method 1 :  m = zeros(M,N)

 

Ex)

Input

 m = zeros(4,2)

Output

 m =

   0   0

   0   0

   0   0

   0   0

 

 

Method 2 :  m = zeros(M) // M x M square matrix

 

Ex)

Input

 m = zeros(3)

Output

 m =

   0   0   0

   0   0   0

   0   0   0

 

 

< Creating a M x N one matrix >

 

Method 1 :  m = ones(M,N)

 

Ex)

Input

 m = ones(4,2)

Output

 m =

   1   1

   1   1

   1   1

   1   1

 

 

Method 2 :  m = ones(M) // M x M square matrix

 

Ex)

Input

 m = one(3)

Output

 m =

   1   1   1

   1   1   1

   1   1   1

 

 

< Mathematical Operation >

 

Case 1 : m = matrix1 + matrix 2;

 

Ex)

Input

m1 = [1 2 3; 4 5 6; 7 8 9];

m2 = [9 8 7; 6 5 4; 3 2 1];

m = m1 + m2

Output

 m =

   10   10   10

   10   10   10

   10   10   10

 

 

Case 2 : m = matrix1 .* matrix 2; // element by element multiplication

 

Ex)

Input

m1 = [1 2 3; 4 5 6; 7 8 9];

m2 = [9 8 7; 6 5 4; 3 2 1];

m = m1 .* m2

Output

 m =

    9   16   21

   24   25   24

   21   16    9

 

 

Case 3 : m = matrix1 * matrix 2; // Inner Product

 

Ex)

Input

m1 = [1 2 3; 4 5 6; 7 8 9];

m2 = [9 8 7; 6 5 4; 3 2 1];

m = m1 * m2

Output

 m =

    30    24    18

    84    69    54

   138   114    90

 

 

Case 4 : m = matrix1 .^ n; // power of n for each element

 

Ex)

Input

m1 = [1 2 3; 4 5 6; 7 8 9];

m2 = [9 8 7; 6 5 4; 3 2 1];

m = m1 .^ 2;

Output

 m =

    1    4    9

   16   25   36

   49   64   81

 

 

Case 5 : m = matrix1 ^ n; // matrix power

 

Ex)

Input

m1 = [1 2 3; 4 5 6; 7 8 9];

m2 = [9 8 7; 6 5 4; 3 2 1];

m = m1 ^ 2;

Output

 m =

    30    36    42

    66    81    96

   102   126   150

 

 

Case 6 : tm = m'; // transpose matrix

 

Ex)

Input

m = [1 2 3; 6 5 4; 7 3 9];

tm=m'

Output

 tm =

     1   6   7

     2   5   3

     3   4   9

 

 

Case 7 : im = inv(m); // take the inverse matrix

 

Ex)

Input

m = [1 2 3; 6 5 4; 7 3 9];

im=inv(m)

Output

im = 

  -0.47143   0.12857   0.10000

   0.37143   0.17143  -0.20000

   0.24286  -0.15714   0.10000

 

 

Case 8 : im = det(m); // take the determinant of the matrix

 

Ex)

Input

m = [1 2 3; 6 5 4; 7 3 9];

dm=det(m)

Output

dm = 

  -70

 

 

< Indexing the elements - matrixname(rowindex,colindex) >

 

Ex)

Input

m = [1 2 3 4;5 6 7 8;9 10 11 12];

m(1,2)

Output

ans = 2

 

Ex)

Input

m = [1 2 3 4;5 6 7 8;9 10 11 12];

m(1,2) = 0

Output

m =

    1    0    3    4

    5    6    7    8

    9    10   11   12

 

 

< Indexing the elements - matrixname(:,colindex) >

 

Ex)

Input

m = [1 2 3 4;5 6 7 8;9 10 11 12];

m(:,2)

Output

ans =

2

6

10

 

Ex)

Input

m = [1 2 3 4;5 6 7 8;9 10 11 12];

m(:,2) = 0

Output

m =

    1    0    3    4

    5    0    7    8

    9    0   11   12

 

Ex)

Input

m = [1 2 3 4;5 6 7 8;9 10 11 12];

m(:,2) = [15;16;17]

Output

m =

    1    15    3    4

    5    16    7    8

    9    17   11   12

 

Ex)

Input

m = [1 2 3 4;5 6 7 8;9 10 11 12];

m(:,2) = [15 16 17]'

Output

m =

    1    15    3    4

    5    16    7    8

    9    17   11   12

 

Ex)

Input

m = [1 2 3 4;5 6 7 8;9 10 11 12];

m(:,2) = [15 16 17].'

Output

m =

    1    15    3    4

    5    16    7    8

    9    17   11   12

 

 

< Indexing the elements - matrixname(rowindex,:) >

 

Ex)

Input

m = [1 2 3 4;5 6 7 8;9 10 11 12];

m(2,:)

Output

ans =

5 6 7 8

 

Ex)

Input

m = [1 2 3 4;5 6 7 8;9 10 11 12];

m(2,:) = 0

Output

m =

    1    2    3    4

    0    0    0    0

    9   10   11   12

 

Ex)

Input

m = [1 2 3 4;5 6 7 8;9 10 11 12];

m(2,:) = [15 16 17 18]

Output

m =

    1    2    3    4

   15   16   17   18

    9   10   11   12

 

 

 

< Matrix Operators >

 

Case 1 : Eigenvalue and Eigenvector

 

Ex)

Input

A = [1.01 0;0 0.9];

[v,d]=eig(A)

Output

v =

 

   0   1

   1   0

 

d =

 

Diagonal Matrix

 

   0.90000         0

         0   1.01000

Input

A*v

Output

ans =

 

   0.00000   1.01000

   0.90000   0.00000

Input

v*d

Output

ans =

 

   0.00000   1.01000

   0.90000   0.00000

 

 

< Decomposition - LU Decomposition >

 

Ex)

Input

m = [1 2 3 4;5 6 7 8;9 10 11 12;13 14 15 16]

Output


m = 

    1    2    3    4

    5    6    7    8

    9   10   11   12

   13   14   15   16

Input

[L,U] = lu(m)

Output

L = 

   0.07692   1.00000   0.00000   0.00000

   0.38462   0.66667  -0.63988   1.00000

   0.69231   0.33333   1.00000   0.00000

   1.00000   0.00000   0.00000   0.00000

 

U = 

   13.00000   14.00000   15.00000   16.00000

    0.00000    0.92308    1.84615    2.76923

    0.00000    0.00000   -0.00000   -0.00000

    0.00000    0.00000    0.00000    0.00000

Input

L * U
Output

ans = 

    1    2    3    4

    5    6    7    8

    9   10   11   12

   13   14   15   16

 

 

< Rearranging Elements - circshift() >

 

Case 1 : m = circshift(m1,N) // Where N is a positive Number. This shift rows

 

Ex)

Input

m1 = [1 2 3; 4 5 6; 7 8 9];

m = circshift(m1,1)

Output

 m =

    7   8   9

    1   2   3

    4   5   6

 

 

Case 2 : m = circshift(m1,N) // Where N is a Negative Number. This shift rows

 

Ex)

Input

m1 = [1 2 3; 4 5 6; 7 8 9];

m = circshift(m1,-1)

Output

 m =

   4   5   6

   7   8   9

   1   2   3

 

 

Case 3 : m = circshift(m1,[0 N]) // Where N is a Positive Number. This shift cols

 

Ex)

Input

m1 = [1 2 3; 4 5 6; 7 8 9];

m = circshift(m1,[0 1])

Output

 m =

   3   1   2

   6   4   5

   9   7   8

 

 

Case 3 : m = circshift(m1,[0 N]) // Where N is a Negative Number. This shift cols

 

Ex)

Input

m1 = [1 2 3; 4 5 6; 7 8 9];

m = circshift(m1,[0 1])

Output

 m =

   2   3   1

   5   6   4

   8   9   7

 

 

< Rearranging Eelemetns - resize() >

 

Case 1 : m = resize(m1,M,N,..)

// Resize Matrix m1 to be an M x N x .. matrix, where M, N is smaller than the original matrix

 

Ex)

Input

m1 = [1 2 3; 4 5 6; 7 8 9];

m = resize(m1,3,2)

Output

 m =

   1   2

   4   5

   7   8

 

 

Case 2 : m = resize(m1,M,N,..)

// Resize Matrix m1 to be an M x N x .. matrix, where M or N is smaller than the original matrix

 

Ex)

Input

m1 = [1 2 3; 4 5 6; 7 8 9];

m = resize(m1,4,5)

Output

 m =

   1   2   3   0   0

   4   5   6   0   0

   7   8   9   0   0

   0   0   0   0   0

 

 

Case 3 : m = resize(m1,M) // Resize Matrix m1 to be an M x M  matrix

 

Ex)

Input

m1 = [1 2 3; 4 5 6; 7 8 9];

m = resize(m1,2)

Output

 m =

   1   2   

   4   5  

 

 

 

 

root@autodl-container-5776409e39-c4febd95:~# python train1.py Traceback (most recent call last): File "/root/train1.py", line 10, in <module> data = scipy.io.loadmat('newdata1_8.mat') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/root/miniconda3/lib/python3.12/site-packages/scipy/io/matlab/_mio.py", line 235, in loadmat matfile_dict = MR.get_variables(variable_names) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/root/miniconda3/lib/python3.12/site-packages/scipy/io/matlab/_mio5.py", line 333, in get_variables res = self.read_var_array(hdr, process) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/root/miniconda3/lib/python3.12/site-packages/scipy/io/matlab/_mio5.py", line 291, in read_var_array return self._matrix_reader.array_from_header(header, process) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "scipy/io/matlab/_mio5_utils.pyx", line 665, in scipy.io.matlab._mio5_utils.VarReader5.array_from_header File "scipy/io/matlab/_mio5_utils.pyx", line 694, in scipy.io.matlab._mio5_utils.VarReader5.array_from_header File "scipy/io/matlab/_mio5_utils.pyx", line 768, in scipy.io.matlab._mio5_utils.VarReader5.read_real_complex File "scipy/io/matlab/_mio5_utils.pyx", line 445, in scipy.io.matlab._mio5_utils.VarReader5.read_numeric File "scipy/io/matlab/_mio5_utils.pyx", line 350, in scipy.io.matlab._mio5_utils.VarReader5.read_element File "scipy/io/matlab/_streams.pyx", line 171, in scipy.io.matlab._streams.ZlibInputStream.read_string File "scipy/io/matlab/_streams.pyx", line 147, in scipy.io.matlab._streams.ZlibInputStream.read_into File "scipy/io/matlab/_streams.pyx", line 134, in scipy.io.matlab._streams.ZlibInputStream._fill_buffer zlib.error: Error -3 while decompressing data: incorrect data check
07-10
<think>我们正在处理一个关于使用scipy.io.loadmat加载.mat文件时出现的zlib解压错误的问题。错误信息为“zlib.error: incorrect data check”,这通常意味着文件在解压缩过程中校验失败,可能是文件损坏或不完整。 根据用户提供的引用,我们知道使用scipy.io.loadmat加载.mat文件的基本方法,但这里遇到了zlib错误。 解决方案思路: 1. 确认文件是否完整:检查文件是否下载完整,没有损坏。可以尝试重新下载或从其他来源获取文件。 2. 尝试使用其他工具读取:例如,使用MATLABOctave尝试打开该文件,以确认文件本身没有问题。 3. 使用其他Python库:例如,使用h5py库(如果文件是HDF5格式的.mat文件,即MATLAB 7.3版本以上保存的)来读取。因为scipy.io.loadmat不支持读取7.3以上的版本(除非使用特定参数,但7.3版本是HDF5格式,需要h5py)。 4. 如果文件是旧版本(7.2及以下),但依然出现此错误,可能是文件损坏。可以尝试使用scipy.io.loadmat的`verify_compressed_data_integrity`参数设置为False,但这样做会跳过数据完整性检查,可能能读取但数据可能不完整或错误。 5. 如果文件是压缩的,尝试手动解压:MATLAB.mat文件(7.3版本以下)默认使用zlib压缩,如果文件头损坏,可能无法解压。可以尝试使用zlib库手动修复。 步骤详解: 首先,检查文件版本: - MATLAB 7.3及以后的版本使用HDF5格式存储,文件开头会有字符串'HDF'。 - 旧版本的文件开头是'MATLAB'。 我们可以用以下代码检查文件头: ```python with open('filename.mat', 'rb') as f: header = f.read(6).decode('ascii', errors='ignore') print(header) # 如果是旧版本,应该为'MATLAB' ``` 如果文件是HDF5格式(即开头为'HDF'),那么我们必须使用h5py来读取。 如果文件是旧版本,但scipy.io.loadmat报错,我们可以尝试以下方法: 方法1:关闭数据完整性检查(谨慎使用) ```python data = sio.loadmat('filename.mat', verify_compressed_data_integrity=False) ``` 方法2:尝试使用其他库(如mat73)读取,但mat73只支持7.3版本的HDF5格式,所以对于旧版本不适用。 方法3:如果文件损坏,尝试修复。可以尝试使用zlib直接解压文件内容。但注意,.mat文件的结构不仅仅是压缩数据,它有一个特定的结构。我们可以尝试读取文件并跳过文件头,然后解压数据部分。这需要了解.mat文件格式。 由于手动修复比较复杂,这里提供一个尝试修复的思路(仅适用于旧版本.mat文件): - 读取整个文件。 - 跳过文件头(前128字节),然后读取数据部分。数据部分由多个数据块(tag)组成,每个数据块包括数据类型、数据大小压缩标志等。如果数据块被压缩,则使用zlib解压。 - 如果某个数据块解压失败,则跳过该块。这样可能会丢失部分数据,但可能能读取其他部分。 但是,这种方法需要深入理解.mat文件格式,实现起来较复杂。因此,作为替代,我们可以尝试使用以下工具: - 使用MATLAB的`load`命令并重新保存为未压缩的格式(v7.3格式或旧版本的未压缩格式)。 - 使用MATLAB的命令:`load('filename.mat'); save('newfile.mat', '-v6');` 因为v6版本不压缩,然后尝试用scipy读取newfile.mat。 如果用户没有MATLAB,可以使用Octave(开源)来执行类似操作。 另外,用户提到参考引用[1]中使用了`r"filename"`,这里要注意文件路径是否正确,以及文件是否被其他程序占用。 总结步骤: 1. 检查文件路径是否正确,文件是否存在。 2. 检查文件版本(HDF5还是旧版本)。 3. 如果是旧版本,尝试使用`verify_compressed_data_integrity=False`。 4. 如果是HDF5格式,使用h5py读取。 5. 如果以上都不行,尝试用MATLAB/Octave修复文件并重新保存。 6. 尝试重新下载或获取原始文件。 代码示例: 情况1:旧版本文件,使用scipy跳过校验 ```python import scipy.io as sio data = sio.loadmat('filename.mat', verify_compressed_data_integrity=False) ``` 情况2:HDF5格式(7.3及以上版本) ```python import h5py with h5py.File('filename.mat', 'r') as f: # 读取变量,注意变量名前面会加上'#',或者使用f.keys()查看 # 例如,读取变量'data' data = f['data'][:] ``` 注意:使用h5py读取的变量是HDF5数据集对象,可能需要转换为numpy数组。 如果用户无法确定文件版本,可以编写一个自动判断的函数: ```python def load_mat_file(filename): # 先检查文件头 with open(filename, 'rb') as f: header = f.read(6).decode('ascii', errors='ignore') if header == 'MATLAB': # 旧版本 try: return sio.loadmat(filename) except Exception as e: print(f"使用scipy读取时出错: {e}") # 尝试跳过校验 try: return sio.loadmat(filename, verify_compressed_data_integrity=False) except Exception as e2: print(f"跳过校验后仍然出错: {e2}") raise else: # 可能是HDF5格式 try: import h5py with h5py.File(filename, 'r') as f: # 这里我们只是返回h5py文件对象,因为读取整个文件到内存可能不现实,需要用户指定变量 # 或者我们可以读取所有变量到一个字典(但注意,h5py的数据集是延迟加载的) data = {} for key in f.keys(): data[key] = f[key][:] return data except Exception as e3: print(f"使用h5py读取时出错: {e3}") raise # 使用 data = load_mat_file('filename.mat') ``` 但是,请注意,HDF5格式的.mat文件在h5py中读取时,变量名可能原始MATLAB中的不完全一致(特别是结构体单元格数组),需要进一步处理。 由于问题复杂,我们提供上述多种方法供用户尝试。 相关问题: 1. 如何检查MATLAB数据文件(.mat)的版本? 2. 使用h5py读取.mat文件时如何处理结构体单元格数组? 3.Octave中如何将.mat文件保存为旧版本或未压缩格式? 4. 除了scipyh5py,还有哪些Python库可以读取.mat文件?</think>### 解决 `scipy.io.loadmat` 中的 zlib 解压错误 当使用 `scipy.io.loadmat` 加载 `.mat` 文件时遇到 `zlib.error: incorrect data check` 错误,通常是由于文件损坏、压缩格式不兼容或文件版本问题导致的。以下是系统化的解决方案: --- #### 1. **检查文件完整性** - **验证文件来源**:确保文件未在传输过程中损坏(如不完整下载)。 - **重新下载文件**:尝试从原始来源重新下载文件。 - **校验文件哈希值**(如 MD5/SHA256)比对原始文件是否一致。 --- #### 2. **尝试跳过压缩数据校验** `scipy.io.loadmat` 提供 `verify_compressed_data_integrity` 参数,可跳过校验(但需谨慎): ```python import scipy.io as sio data = sio.loadmat("filename.mat", verify_compressed_data_integrity=False) ``` > **注意**:此操作可能加载损坏数据,仅作临时修复[^1]。 --- #### 3. **手动解压文件** 若文件是压缩的 `.mat` 文件(如 `.mat.gz`),先手动解压再加载: ```python import gzip import shutil # 解压 .mat.gz 文件 with gzip.open("filename.mat.gz", 'rb') as f_in: with open("filename.mat", 'wb') as f_out: shutil.copyfileobj(f_in, f_out) # 加载解压后的文件 data = sio.loadmat("filename.mat") ``` --- #### 4. **使用 `h5py` 读取高版本文件** MATLAB v7.3+ 的 `.mat` 文件采用 HDF5 格式,需用 `h5py` 库读取: ```python import h5py with h5py.File("filename.mat", 'r') as f: # 提取变量(如名为 'data' 的变量) data = f['data'][:] ``` > **提示**:通过 `f.keys()` 查看所有变量名[^2]。 --- #### 5. **在 MATLAB/Octave 中修复文件** 若文件来自 MATLAB,尝试在 MATLAB 中修复并重新保存: ```matlab % MATLAB 命令 load('filename.mat'); % 尝试加载 save('new_file.mat', '-v7'); % 保存为旧版格式(兼容 scipy) ``` 或使用 Octave(开源替代): ```bash octave --eval "load('filename.mat'); save('-v7', 'new_file.mat');" ``` --- #### 6. **其他工具修复** - **Python 库 `mat73`**:专用于读取 v7.3 文件: ```python import mat73 data = mat73.loadmat("filename.mat") ``` - **命令行工具 `ncdump`**(HDF5 文件): ```bash ncdump -h filename.mat # 检查文件结构 ``` --- ### 常见原因总结 | 原因 | 解决方案 | |---------------------|-----------------------------| | 文件损坏 | 重新下载/校验文件完整性 | | 压缩数据校验失败 | `verify_compressed_data_integrity=False` | | MATLAB v7.3+ 格式 | 使用 `h5py` 或 `mat73` | | 压缩文件未解压 | 手动解压后再加载 | > 若问题持续,建议提供文件样本进一步分析。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值