Trouble With MATLAB Variable Creation

2 visualizaciones (últimos 30 días)
Isabella
Isabella el 21 de Jul. de 2024
Comentada: Stephen23 el 21 de Jul. de 2024
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 comentarios
Isabella
Isabella el 21 de Jul. de 2024
Editada: Isabella el 21 de Jul. de 2024
Ah, I see. Thank you. How would you suggest implementing the use of a structure?
Stephen23
Stephen23 el 21 de Jul. de 2024
"How would you suggest implementing the use of a structure?"
S = struct();
S.(this(1)) = this(2)

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Productos


Versión

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by