Trouble With MATLAB Variable Creation

조회 수: 2 (최근 30일)
Isabella
Isabella 2024년 7월 21일
댓글: Stephen23 2024년 7월 21일
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
Isabella
Isabella 2024년 7월 21일
편집: Isabella 2024년 7월 21일
Ah, I see. Thank you. How would you suggest implementing the use of a structure?
Stephen23
Stephen23 2024년 7월 21일

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by