Storing elments of marix from text file into variables

3 ビュー (過去 30 日間)
Mohammad Zaved Siddiqui
Mohammad Zaved Siddiqui 2015 年 9 月 21 日
I'm having one text file containing a matrix in which the first column is a variable lets say x ,first row is a variable lets say y and all the elements inside except x and y are z.How do I read this text file and store them in separate variables .I tried using this but it didn't work.I think I've not stored the elements in z correctly if yes what should I do to correct it?
input = load('matrix.txt');
x= input(:,1)./100; y= input(1,:); z =input(:,:);
end
  2 件のコメント
Stephen23
Stephen23 2015 年 9 月 21 日
編集済み: Stephen23 2015 年 9 月 21 日
Is that matrix correct? It seems to be missing the first element. Could you confirm if the first row would have four or five elements.
Because of the missing first element there are different ways that this matrix could be read into MATLAB.
Mohammad Zaved Siddiqui
Mohammad Zaved Siddiqui 2015 年 9 月 21 日
編集済み: Mohammad Zaved Siddiqui 2015 年 9 月 21 日
yes it is having four elements only because the first row and first column are variable and other elements are the values at given combination of these two variables

サインインしてコメントする。

採用された回答

Jan
Jan 2015 年 9 月 21 日
編集済み: Jan 2015 年 9 月 21 日
This is a bad method to store data, because Matlab must guess the size of the data.
fid = fopen(FileName, 'r');
if fid==-1, error(Cannot open file: %s', FileName); end
FirstLine = fgets(fid);
y = sscanf(FirstLine, '%f');
n = length(y);
M = fscanf(fid, '%f', [n+1, Inf]);
fclose(fid);
x = M(:, 1);
Data = M(:, 2:n+1);
Perhaps you need some transpose operators to get the wanted orientations.
  3 件のコメント
Jan
Jan 2015 年 9 月 22 日
If you post the error messages, finding an improvement is easier. I cannot run Matlab during the daytime, so it is possible that the code contains a bug. But you can either fix it by you own or help me finding it. At least this code should contain enough ideas to allow you to solve the problem.
Mohammad Zaved Siddiqui
Mohammad Zaved Siddiqui 2015 年 9 月 25 日
I used the same code and fixed it myself.thanks for the help

サインインしてコメントする。

その他の回答 (1 件)

Thorsten
Thorsten 2015 年 9 月 21 日
Based on Jan's solution, I wrote the following function that does the job:
function [x y data] = readxydata(filename)
fid = fopen(filename, 'r');
if fid == -1, error('Cannot open file: %s', filename); end
y = sscanf(fgets(fid), '%f');
data = fscanf(fid, '%f', [numel(y)+1, Inf])';
st = fclose(fid);
if st ~= 0, error('Cannot close file: %s', filename); end
x = data(:, 1);
data = data(:, 2:end);
  1 件のコメント
Mohammad Zaved Siddiqui
Mohammad Zaved Siddiqui 2015 年 9 月 25 日
Showing error "Error: File: matrix_read_3_var.m Line: 3 Column: 1 Function definitions are not permitted in this context."

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by