2016-08-11 3 views
0

데이터 파일이 matrix.txt인데 세 개의 열이 있습니다. 첫 번째 열은 행 인덱스를 저장하고 두 번째 열은 열 인덱스를 저장하고 세 번째 열은 값을 저장합니다. 어떻게 이것을 mat이라는 행렬로 읽습니까? 명시 적으로 말하자면 matn*n 정사각형 행렬이고, 예를 들어 n=2이라고합시다. 텍스트 파일에서는이 있습니다Matlab : 매트릭스로 데이터를 읽는 방법

0 0 10 
1 1 -10 

지정되지 mat의 요소는 0입니다. 따라서 mat은 다음과 같아야합니다.

mat = 10 0 
     0 -10 

어떻게해야합니까?

+0

행렬이 정사각형이라고 알려져 있습니까? ? –

답변

1

일반 2-D 케이스의 경우 작동합니다. 샘플 matrix.txt 사용

% 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 

:

0 0 10 
1 1 -10 
1 2 20 

우리가 나타납니다

>> mat 

mat = 

    10  0  0 
    0 -10 20 
1

을 MATLAB에 있기 때문에, 인덱스 1 (안 제로)로 시작, 우리는 우리의 인덱스에 1을 추가해야합니다 암호.
rc은 행과 열을 나타냅니다.
또한 mn는 n은 영 행렬 m입니다

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]); 
관련 문제