Reputation:
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
?
Upvotes: 1
Views: 1161
Reputation: 1
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
Upvotes: 0
Reputation: 78364
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.
Upvotes: 2
Reputation: 445
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,';'));
Upvotes: 0