我想动态读取数据并从文本文件分配数据值。
这是文本文件:
object crop_image.nii
plane 3
coeff -5.046e-19 3.168e-13 -5.716e-8 0.005 2.746
amax 1
nfact 1
pt .9906
suvr 1
regi 1
最初,我是在使用这段代码(有效)来阅读它的。
readin = readlines(insert text file name here);
for i = 1:length(readin)
this = split(readin(i))';
switch this(1)
case 'object'
object = this{2};
case 'plane'
plane = str2double(this{2});
case 'coeff'
coeff = str2double(this(2:end));
case 'suvr'
suvr = str2double(this{2});
case 'amax'
amax = str2double(this{2});
case 'nfact'
nfact = str2double(this{2});
case 'pt'
pt = str2double(this{2});
case 'regi'
regi = str2double(this{2});
otherwise
fprintf('Invalid delimiter: %s! Please check your text file.\n', this{1});
return;
end
end
但是巨大的开关盒并不能真正起到修饰作用。我想代码是否有效并不重要,但仍然如此。我希望它更精致。
哦,是的,所有元胞数组内容(以及巨大的 switch 情况)的原因是因为我将从 Linux 运行这段代码(这段代码是一个更大的脚本的一部分)。另外,文本文件不能保证按照对象、平面、系数等的顺序出现,这就是为什么我让代码检测第一个单词。
无论如何,我认为我可以使用 allocatein 函数解决我的问题,但它不起作用?这是我到目前为止所拥有的。
if ismember(this(1), ["object", "plane", "coeff", "suvr", "amax", "nfact", "pt", "regi"])
if isa(this(2), 'string')
assignin('base', this(1), this(2));
else
assignin('base', this(1), str2double(this(2:end)));
end
else
fprintf('Invalid delimiter: %s! Please check your text file.\n', this(1));
return;
end
我已经尽力调试了。该代码没有跳过 allocatein 函数。该行代码正在执行,但是当它执行时,什么也没有发生。
就像,我在脚本调用 allocatein 函数之前检查了 this(1) 和 this(2) 的值。是的,this(1) 等于“object”,this(2) 等于对象名称,也是一个字符串,但是当执行 allocatein 行代码时,什么也没有显示。我不明白。将不胜感激任何和所有的建议。谢谢。
应该尽可能避免eval
switch
,因为您将所有内容都视为相同(转换为双精度),除非它是
object
行,所以您可以将其作为特殊情况处理。我在下面的代码中添加了注释来解释每个步骤。从您的示例中我不确定每个文件是否也可能有多个对象,因此我使用附加索引来处理这种情况
idx
。
readin = readlines('temp.txt');
% Initialise output struct
out = struct([]);
idx = 0; % current object index
% Loop over file - one string per line
for i = 1:length(readin)
% Split on spaces
this = split(readin(i))';
% Extract the name and value(s) from the line
name = this(1);
val = this(2:end);
if strcmp( name, 'object' )
% new object, increment output index
idx = idx + 1;
else
% Unless this is object name, treat the value as a double
% It doesn't matter if it's scalar or array
val = str2double(val);
end
% Assign to output struct
out(idx).(name) = val;
end
结果: