2016-05-06 27 views
0

Ich schreibe einen Code zur Lösung von Ax = b mit MATLAB's x = A \ B. Ich glaube, mein Problem liegt darin, die Daten aus den Dateien in das Array zu bekommen. Gerade jetzt, der Lösungsvektor kommt heraus, um eine Belastung von 0 zu seinDaten in Array lesen MATLAB

Die Matrizen, die ich verwende, haben jeweils 10 Zeilen. Sie sind in den Textdateien korrekt ausgerichtet.

% solve a linear system Ax = b by reading A and b from input file 
% and then writing x on output file. 
clear; 
clc; 
input_filename = 'my_input.txt'; 
output_filename = 'my_output.txt'; 
% read data from file 
fileID = fopen('a_matrix.txt', 'r'); 
formatSpec = '%d %f'; 
sizeA = [10 Inf]; 



A = load('b_matrix.txt'); 

A = A' 

file2ID = fopen('b_matrix.txt','r'); 
formatSpec2 = '%d %f'; 
sizeB = [10 Inf]; 

b = load('b_matrix.txt'); 
fclose(file2ID); 

b = b' 

% solve the linear system 
x = A\b; 

% write output data on file 


dlmwrite('my_output.txt',x,'delimiter',',','precision',4); 
% print screen 
fprintf('Solution vector is: \n'); 
fprintf('%4.2f \n', x); 

Jede Hilfe würde sehr geschätzt werden.

Antwort

0

Ich beantwortete meine eigene Frage, aber ich fühlte die Notwendigkeit zu teilen, falls jemand andere ähnliche Probleme hat.

% solve a linear system Ax = b by reading A and b from input file 
% and then writing x on output file. 
clear; 
clc; 
input_filename = 'my_input.txt'; 
output_filename = 'my_output.txt'; 
% read data from file 
f = textread('a_matrix.txt', '%f'); 
vals = reshape(f, 11, []).'; 
A = vals(:,1:10); 
b = vals(:,11); 

% solve the linear system 
x = A\b; 

% write output data on file 

dlmwrite('my_output.txt',x,'delimiter',',','precision',4); 
% print screen 
fprintf('Solution vector is: \n'); 
fprintf('%4.2f \n', x); 

Ich endete die Kombination der 'a' und 'b' Matrix in einer einzigen Textdatei zur Vereinfachung. Jetzt liest MATLAB die Daten in Spalten ein, daher ist es notwendig, 'reshape' zu verwenden, um die Daten innerhalb des Arrays korrekt anzupassen. Dann habe ich die Informationen aus der einzelnen Matrix nach Spalten herausgefiltert, wobei ich die Funktion 'vals' verwendet habe, wie sie in meinem Code zu sehen ist. Die "A" -Matrix ist im Wesentlichen alle Zahlen in den Spalten 1 bis 10, während die "B" -Matrix die elfte (und letzte) Spalte ist.

Mit der MATLAB-Funktion x = A \ b konnte ich das lineare Gleichungssystem lösen.