문제

Hi all I have a problem in matlab .

I have a text file in which the data is delimited by spaces. An example is given as follws :

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

What I want to do is to read the text file & generate matrices like this :

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)

How can I do this matlab ?

Thanks in advance !!

Please do check the edits. Updated the sizes of the matrix to be extracted!

도움이 되었습니까?

해결책

Let's do it step by step:

  1. First we read the lines as strings:

    fid = fopen(filename, 'r');
    C = textscan(fid, '%s', 'Delimiter', '\n');
    fclose(fid);
    
  2. Then we convert the lines into numerical values:

    C = cellfun(@str2num, C{:}, 'UniformOutput', false);
    
  3. To group the values together into matrices, we could do something like so:

    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};
    

Hope this helps!

다른 팁

Considering that you trust your input file to be always structured like that, then you shall use fgetl(file_descriptor) to read your file line by line. Then you can split each line (string) using the white space as a delimiter.

Finally, for the matrix A, you just need to append the lines to that matrix until you get to the (last-1) line.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top