2016-08-11 118 views
0

我有一個數據文件matrix.txt,它有三列。第一列存儲行索引,第二列存儲列索引,第三列存儲值。我如何將這些讀入到稱爲mat的矩陣中。明確地說,假設我們的mat是一個n*n方陣,例如n=2。在文本文件中,它具有:Matlab:如何將數據讀入矩陣

0 0 10 
1 1 -10 

沒有指定在mat的元素是0。因此mat應該是:

mat = 10 0 
     0 -10 

我該如何做到這一點?

+0

是否已知矩陣是正方形? –

回答

1

這應該適用於一般的二維情況。

% 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

因爲在MATLAB中,指數1(不爲零)開始,我們應該加1,我們的指數在碼。
rc代表行列。
mn是對於m乘n零矩陣

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 
1

我看到我太慢了,但我決定後我的回答反正...
我初始化矩陣A作爲矢量,並用於重塑:

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