大家好我在matlab中遇到了问题。
我有一个文本文件,其中数据由空格分隔。下面给出一个例子:
3 4
1 3 6
2 4 5 7
1 3 0
0 0 -1 -2
1 -1 0 -1
-1 0 -2 0
1 -1 2 3 1
我想要做的是阅读文本文件&生成这样的矩阵:
size_mat=[3,4];
B=[1,3,6];
NB=[2,4,5,7];
b=[1,3,0];
A=[0, 0, -1, -2;
1, -1, 0, -1;
-1, 0, -2, 0];
z=[1,-1,2,3,1];
%//In details I can highlight these points :
%//1st line is the size_mat matrix. This has always dimension 1X2. m=size_mat(1) & n=size_mat(2)
%//2nd line is the B matrix. Dimension is 1Xm
%//3rd line is the NB matrix Dimension is 1Xn
%//4th line is the b matrix Dimension is 1Xm
%//Starting from 5th line to the (last-1) line is my A matrix
%//whose size is actually equal to mXn where m=size_mat(1) & n=size_mat(2)
%//Last line is the z matrix Dimension is 1X(n+1)
我该怎么做这个matlab?
提前致谢!!
请检查修改。更新了要提取的矩阵的大小!
答案 0 :(得分:2)
让我们一步一步来做:
首先我们将这些行读作字符串:
fid = fopen(filename, 'r');
C = textscan(fid, '%s', 'Delimiter', '\n');
fclose(fid);
然后我们将这些行转换为数值:
C = cellfun(@str2num, C{:}, 'UniformOutput', false);
要将值组合成矩阵,我们可以这样做:
size_mat = C{1};
B = C{2};
NB = C{3};
b = C{4};
A = vertcat(C{5:end - 1}); %// or: A = cell2mat(C(5:end - 1));
z = C{end};
希望这有帮助!
答案 1 :(得分:1)
考虑到您相信您的输入文件始终是这样的结构,那么您应该使用fgetl(file_descriptor)逐行读取您的文件。然后,您可以使用空格作为分隔符来分割每一行(字符串)。
最后,对于矩阵A,您只需要将线附加到该矩阵,直到到达(last-1)行。