Matlab:如何将数据读入矩阵

时间:2016-08-11 15:11:30

标签: matlab file matrix

我有一个数据文件matrix.txt,它有三列。第一列存储行索引,第二列存储列索引,第三列存储值。如何将这些内容读入名为mat的矩阵中。明确地说,假设我们的matn*n方阵,例如让n=2。在文本文件中,它具有:

0 0 10
1 1 -10

未指定mat中的元素是0。因此mat应该是:

mat = 10   0
      0   -10

我如何实现这一目标?

3 个答案:

答案 0 :(得分:1)

这适用于通用2-D案例。

% Read in matrix specification
fID = fopen('matrix.txt');
tmp = fscanf(fID, '%u%u%f', [3 inf])';
fclose(fID);

% Use the maximum row and column subscripts to obtain the matrix size
tmp(:, 1:2) = tmp(:, 1:2) + 1;  % MATLAB doesn't use 0-based indexing
matsize = [max(tmp(:,1)), max(tmp(:,2))];

% Convert subscripts to linear indices
lidx = sub2ind(matsize, tmp(:,1), tmp(:,2));

mat = zeros(matsize);  % Initialize matrix
mat(lidx) = tmp(:,3);  % Assign data

使用示例matrix.txt

0 0 10
1 1 -10
1 2 20

我们收到:

>> mat

mat =

    10     0     0
     0   -10    20

答案 1 :(得分:1)

因为在MATLAB中,索引以1(非零)开头,所以我们应该在代码中将索引加1 rc代表行和列 此外,mn用于m by n zero matrix

A = importdata('matrix.txt');
r = A(:, 1)';
c = A(:, 2)';
m = max(r);
n = max(c);
B = zeros(m + 1, n + 1);
for k = 1:size(A,1);
    B(r(k) + 1, c(k) + 1) = A(k, 3);
end

结果:

B =

    10     0
     0   -10

答案 2 :(得分:1)

我觉得我太慢了,但无论如何我决定发布我的答案...... 我将矩阵A初始化为矢量,并使用了reshape:

%Load all file to matrix at once
%You may consider using fopen and fscanf, in case Matrix.txt is not ordered perfectly.
row_column_val = load('Matrix.txt', '-ascii');

R = row_column_val(:, 1) + 1; %Get vector of row indexes (add 1 - convert to Matalb indeces).
C = row_column_val(:, 2) + 1; %Get vector of column indexes (add 1 - convert to Matalb indeces).
V = row_column_val(:, 3);     %Get vector of values.

nrows = max(R); %Number of rows in matrix.
ncols = max(C); %Number of columns in matrix.

A = zeros(nrows*ncols, 1); %Initialize A as a vector instead of a matrix (length of A is nrows*ncols).

%Put value v in place c*ncols + r for all elements of V, C and R.
%The formula is used for column major matrix (Matlab stored matrices in column major format).
A((C-1)*nrows + R) = V;

A = reshape(A, [nrows, ncols]);