How to load text file to workspace variables?

15 ビュー (過去 30 日間)
Tom Karlsson
Tom Karlsson 2019 年 10 月 25 日
コメント済み: Stephen23 2019 年 10 月 27 日
Hi,
I wonder how to read/load variables from text file to matlab, with following format:
var1 val1
var2 val2
var3 val3
var4 val4
I want them to be loaded to workspace as variables with string name in var and numeric value as val.
  2 件のコメント
dpb
dpb 2019 年 10 月 26 日
In general, that's a bad idea -- use MATLAB array syntax instead.
Stephen23
Stephen23 2019 年 10 月 26 日
Use indexing.
Indexing is neat, simple to debug, and very efficient (unlike what you are trying to do).

サインインしてコメントする。

回答 (1 件)

per isakson
per isakson 2019 年 10 月 26 日
編集済み: per isakson 2019 年 10 月 26 日
"load to workspace as variables with string name in var and numeric value as val." There need to be a really good reason to do that, because it comes at a cost. Read Why Variables Should Not Be Named Dynamically and then read Magically Making Variables Appear in a Workspace is Risky a second time.
After reading try
cssm
which outputs
Name Size Bytes Class Attributes
S 1x1 736 struct
var1 1x1 8 double
var2 1x1 8 double
var3 1x1 8 double
var4 1x1 8 double
where (in one m-file named cssm.m)
%%
fid = fopen( 'cssm.txt' );
cac = textscan( fid, '%s%f' );
fclose( fid );
%%
for jj = 1 : length(cac{1})
S.( cac{1}{jj} ) = cac{2}(jj); % dynamic names in a structure
assign( cac{1}{jj}, cac{2}(jj) ) % magically "poof" variables
end
whos S v*
function assign( name, val )
assignin( 'caller', name, val );
end
and where cssm.txt contains
var1 1
var2 2
var3 3
var4 4
Finally, are there any good reasons not to use "dynamic names in a structure" ?
  1 件のコメント
Stephen23
Stephen23 2019 年 10 月 27 日
A table would also be a good choice.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by