0

私は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} };

たとえばexportMatrix()、2つの引数を持つMATLAB関数が必要です。

  • MATLABマトリックス
  • このマトリックスをエクスポートする必要があるtipo

この関数の使用方法の2つの例は次のとおりです。

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

また、行列が多次元の場合、関数はそれを正しくエクスポートする必要があります。たとえば、次の場合:

>> size(A)

ans =

        100        10           3

その場合、呼び出しの結果は次のよう exportMatrix( A, 'double');になります。

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

1 に答える 1

0

それは楽しい質問でした:)ここに出発点があります:

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));

これは2Dアレイ以上でのみ機能します。たとえば試してみてください。

exportMatrix(rand(2,2,2))

ファイルに出力する場合は、fprintfステートメントを変更する必要があります。

于 2013-03-21T15:02:19.650 に答える