【问题标题】:How to export a generic MATLAB matrix to a text file, formatted like C# array如何将通用 MATLAB 矩阵导出到文本文件,格式类似于 C# 数组
【发布时间】:2013-03-21 12:10:01
【问题描述】:

我在 MATLAB 中有一个矩阵,如下所示:

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

我想将其导出为 C# 格式的文本文件:

double[,] myMat = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12} };

我需要一个 MATLAB 函数,例如称为 exportMatrix(),带有两个参数:

  • MATLAB 矩阵
  • 必须导出此矩阵的类型

如何使用此功能的两个示例如下:

exportMatrix( myMatrix1, 'short');
exportMatrix( myMatrix2, 'float');

如果矩阵是多维的,我还需要该函数正确导出它。例如,如果:

>> size(A)

ans =

        100        10           3

那么调用exportMatrix( A, 'double');的结果应该是:

double[, ,] A = {...};

【问题讨论】:

标签: c# matlab export


【解决方案1】:

这是一个有趣的问题 :) 这是一个起点:

function exportMatrix(A)
% get dimensions 
dimensions  = size(A);
N_dim       = length(dimensions);

% print variable declaration to console
fprintf('double[')
for i = 1:N_dim-1
    fprintf(',')
end
% finish declaration and print rows of matrix
fprintf('] A= {%s}\n', exportRow(A, dimensions))

function str_out = exportRow(B, dims)
% recursively print matrix

% init output string
str_out = '';

% have we finished yet?
if length(dims) > 1
    % if not, then go to next layer
    for i=1:dims(1)
        % this test is just to make sure that we do not reshape a
        % one-dimensional array
        if length(dims) > 2
            % print next slice inside curly-braces
            str_out = sprintf('%s{ %s },', str_out, exportRow(reshape(B(i,:), dims(2:end)), dims(2:end)) );
        elseif length(dims) == 2
            % we are almost at the end, so do not use reshape, but stil
            % print in curly braces
            str_out = sprintf('%s{ %s },', str_out, exportRow(B(i,:), dims(2:end)) );
        end
    end
else
    % we have found one of the final layers, so print numbers
    str_out = sprintf('%f, ', B);
    % strip last space and comma
    str_out = str_out(1:end-2);
end
% strip final comma and return
str_out = sprintf('%s', str_out(1:end-1));

仅适用于二维数组及以上。尝试例如。

exportMatrix(rand(2,2,2))

如果要打印到文件,则需要更改 fprintf 语句...

【讨论】:

  • 这是一个很好的起点。你也可以用另一个表示C#中矩阵类型的输入来修改上面的函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-21
  • 1970-01-01
相关资源
最近更新 更多