MATLAB Answers

Import variable names and vaues from a .txt file

68 views (last 30 days)
Tom
Tom on 13 Feb 2020
Edited: Stephen Cobeldick on 8 Sep 2020
Hello everyone!
I thought I had a really simple question but unfortunately it seems harder than expected.
The problem is the following:
First I generate a .txt file (named inputs.txt) by using another program, this inputs.txt file contains variables names and values in this way:
base 10
length 5
angle 45
height 5
if necessary for the solution, they can be also be organized by columns.
Now I have to import in MATLAB this inputs.txt file assigning the name of the variable to their respective value. For example, I have to load the inputs.txt so that I'll obtain in MATLAB:
base = 10;
length = 5;
angle = 45;
hieght = 5;
I tried many different functions as "readtable", "textread", "load", "import"... I can't find a way to do that. The problem is related to the variables names because they are read as "cells" and I don't know how to convert them in variables. It is really important for me to assign the variables equal to the ones in the .txt file and I have around 50 different inputs variables in the inputs.txt file so I need a smart way to automatically do that without re-writing name variables every time.

Answers (2)

Giuseppe Inghilterra
Giuseppe Inghilterra on 13 Feb 2020
Hi,
you can try "eval" matlab function to solve your problem
For example:
T = readtable(filename,'Delimiter',' ');
[r,c] = size(T);
for ii = 1:r
eval([T.Var1{ii} '=' num2str(T.Var2(ii))])
end
You can use "readtable" function to read .txt file (you can specify delimiter in order to identify each column). Then you apply a for loop cycle in which you use "eval" function that allow you to evaluate matlab expression. This code can solve your problem because it is like you write "base = 10", where "base" is contained in cell array T.Var1{1} and '10' is contained in T.Var2(1). (Var1 and Var2 are default names of columns of table).
Hope this helps

Adrian Cherry
Adrian Cherry on 8 Sep 2020
Edited: Adrian Cherry on 8 Sep 2020
As a Linux user I'd fix the text file before matlab looks at it. Or use system() if you want to do it within Matlab.
You will need gawk or alternative flavour of gawk to simply add an = between the variable name and value and add a ;.
The redirects < takes your text file and reformats it into the m-file inputs.m. Run that an you have your variables in the workspace
system('gawk ''{print $1 " = " $2";"}'' <inputs.txt > inputs.m');
inputs;
You can play tunes if you want it as a structure so this will add "myStruct." to the start or each variable.
system('gawk ''{print "myStruct."$1 " = " $2";"}'' <inputs.txt > inputs.m');
inputs;

Community Treasure Hunt

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

Start Hunting!