assign variable from txt-file
이전 댓글 표시
Hello,
i want to realize the following issue...
I have a given txt-file in such a format:
var1 = a
var2 = b
var3 = c
Now i want to assign these variable in matlab such as var1 = a and var2 = b ... But the vectors a, b, c, d, e and f are part of a big struct, where i can access on each value with that command: data(i).a(j), where i is the struct number and j the position of the value in f.e the vector a.
So if I change my txt-file to:
var1 = d
var2 = e
var3 = f
... I need the values of d in variable var1 which i use in matlab. So in the text-file it is a string but in my matlab program i have to use the string 'd' as a variable name to access the variable d from my struct. After the assignment i want to fill it like that, but i have to use something other than data(i).d(j), because i want the assignment dependant on my txt-file
for i=1:15
for j=1:length(var)
var(:,1) = data(i).d(j);
var(:,2) = data(i).e(j);
var(:,3) = data(i).f(j);
end
end
I hope I've explained my issue quiet understandable and I thank you in advance for any help...
Best regards
Da Ke
댓글 수: 6
Walter Roberson
2019년 1월 21일
You can use fieldnames() to find the names of the variables you received, and you can use dynamic field names to access.
fn = fieldnames(data);
var(:,1) = data.(fn{1});
Image Analyst
2019년 1월 21일
I think you forgot to attach your text file. I'm not really going to put effort into answering this until I see the actual file. For all I know you can just rename the file extension to .m and run it as an m-file.
Daniel Kern
2019년 1월 21일
Daniel Kern
2019년 1월 21일
Daniel Kern
2019년 1월 21일
Walter Roberson
2019년 1월 22일
If you have the data stored as a struct and you know the field name, then data.a . However since that is what you started with, I seem to be missing something.
If you have a cell array in which the first column is a variable name and the second is the corresponding value, then
var_a = YourCell{ strcmp(VariableYouAreLookingFor, YourCell(:,1)), 2};
In the case that the variable is not found, this would be empty. You would probably not want to store directly into an array because you would want to test for the variable being present and having the right size and datatype before storing.
답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Variables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!