Clear Filters
Clear Filters

Trouble With MATLAB Variable Creation

47 views (last 30 days)
Isabella
Isabella on 21 Jul 2024 at 6:10
Commented: Stephen23 on 21 Jul 2024 at 17:24
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 Comments
Isabella
Isabella on 21 Jul 2024 at 17:02
Edited: Isabella on 21 Jul 2024 at 17:03
Ah, I see. Thank you. How would you suggest implementing the use of a structure?

Sign in to comment.

Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2024a

Community Treasure Hunt

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

Start Hunting!