- some of the cases require special handling (so you will anyway need SWITCH or similar)
- it makes the code easy to understand (which improves maintainability)
- it makes debugging much easier
- it is more robust
- it is more efficient
Trouble With MATLAB Variable Creation
2 次查看(过去 30 天)
显示 更早的评论
Hello! I would like to dynamically read in data and assign data values from a text file.
Here is the text file:
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
Initially, I was reading it in using this block of code (which works).
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
But a huge switch case doesn't really give polish. I guess it shouldn't matter if the code works, but still. I'd like it to be more refined.
Oh, yeah, the reason for all the cell array stuff (and for the huge switch case) is because I'll be running this code (this code is a portion of a much larger script) from Linux. Also, the text file isn't guaranteed to come in the order of object, plane, coeff, etc., which is why I have the code detect the first word.
Anyway, I thought I could solve my issue using the assignin function, but it's not working? Here's what I have so far.
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
I've done my best to debug. The code is not skipping over the assignin function. That line of code is executing, but when it executes, nothing happens.
Like, I've checked the values of this(1) and this(2) right before the script calls the assignin function. Yes, this(1) equals "object" and this(2) equals the object name, also a string, but nothing shows up when the assignin line of code executes. I don't get it. Would appreciate any and all suggestions. Thanks.
3 个评论
Stephen23
2024-7-21
"How would you suggest implementing the use of a structure?"
S = struct();
S.(this(1)) = this(2)
Or perhaps using https://www.mathworks.com/help/matlab/ref/cell2struct.html
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!