基于matlab,利用一个函数实现高维矩阵存储读写控制,并举例
时间: 2024-05-09 12:17:23 浏览: 123
函数名称:high_dim_matrix
函数功能:实现高维矩阵存储读写控制
函数输入:
- filename: 存储的文件名
- matrix: 待存储的矩阵
- mode: 存储模式,'w'表示写入,'r'表示读取
函数输出:
- matrix_read: 读取的矩阵
函数示例:
1. 存储一个3维矩阵并读取:
```matlab
% 生成一个3维矩阵
matrix = rand(3, 4, 5);
% 存储矩阵
high_dim_matrix('test.mat', matrix, 'w');
% 读取矩阵
matrix_read = high_dim_matrix('test.mat', [], 'r');
```
2. 存储一个4维矩阵并读取其中一个元素:
```matlab
% 生成一个4维矩阵
matrix = rand(2, 3, 4, 5);
% 存储矩阵
high_dim_matrix('test.mat', matrix, 'w');
% 读取矩阵中的一个元素
matrix_read = high_dim_matrix('test.mat', [], 'r');
elem = matrix_read(1, 2, 3, 4);
```
函数实现:
```matlab
function matrix_read = high_dim_matrix(filename, matrix, mode)
% 高维矩阵存储读写控制函数
% 获取矩阵维数和大小
dim = ndims(matrix);
size_mat = size(matrix);
if dim == 2 && size_mat(2) == 1
dim = 1; % 处理向量
end
if strcmp(mode, 'w') % 写入模式
% 打开文件
fid = fopen(filename, 'w');
if fid == -1
error('Cannot create file %s', filename);
end
% 写入维数和大小信息
fwrite(fid, dim, 'int');
fwrite(fid, size_mat, 'int');
% 写入矩阵数据
fwrite(fid, matrix, 'double');
% 关闭文件
fclose(fid);
elseif strcmp(mode, 'r') % 读取模式
% 打开文件
fid = fopen(filename, 'r');
if fid == -1
error('Cannot open file %s', filename);
end
% 读取维数和大小信息
dim_read = fread(fid, 1, 'int');
size_mat_read = fread(fid, dim_read, 'int');
% 读取矩阵数据
matrix_read = fread(fid, prod(size_mat_read), 'double');
% 将读取的数据重组成矩阵
matrix_read = reshape(matrix_read, size_mat_read);
% 关闭文件
fclose(fid);
else
error('Invalid mode');
end
end
```
阅读全文
相关推荐

















