简体   繁体   中英

How to read matrix from text file in matlab?

I have a text file in the same folder as my matlab code called matlab.in , its contents are

training_set = [1 2 3; 4 5 6]

How do I read this matrix into a variable called training_set ?

Your text file contains an executable Matlab statement. You could, probably even should, rename it to something like training_set.m (the .m suffix is important) and simply 'read' it from the command line by executing it. On my machine the 'command'

>> training_set

generates the response

training_set =

     1     2     3
     4     5     6

and, hey presto, the variable training_set is now safely ensconced in your workspace.

Now congratulate yourself for having written your first (?) Matlab script , reward yourself with a visit to the documentation to review this important topic.

First, open it using fopen(...) :

fid = fopen('matlab.in');

Second, read the line from the file and close the file again, since you don't need it anymore:

content = fgetl(fid);
fclose(fid);

Third, evaluate the string read from the file:

eval(content);

If you wanted to suppress the output, you might either want to add a semicolon at the end of the text file or instead use:

eval(strcat(content,';'));
file1.txt: 1 2 3 4 5 6 7 8
           10 20 30 40 50 60 70 80

    [fileID,errmsg] = fopen('file1.txt')
    val= textscan(fileID, '%u8')
    z = transpose(cell2mat(val))
    vec = transpose(reshape(z, [8 2]))

...

Gives you 
vec =

  2×8 uint8 matrix

    1    2    3    4    5    6    7    8
   10   20   30   40   50   60   70   80

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM