How to extract a field from a structure in a 'for loop', so that it would behave like an array?
조회 수: 7 (최근 30일)
이전 댓글 표시
I have six tables, each with two columns and variable numbers of rows. They are called mi2_1, mic2_2, mic2_3....mic2_6.
I want to load mic2_1, do some stuff with it, the same way I would with any nx2 array, save the result (a scalar) as the first index in "sum". Then load mic2_2 and do similar stuff with it and save it as index 2 in "sum" and so on. So that sum at the end would store 6 results, from the 6 files, that I can then average.
My problem is automating the loading files bit. Looks like the best way to do this is to use sprintf. But I end up with a structure. I've commented out various ways I've tried to get the structure to behave like an array - couldn't get them to work (so if anyone can point out what's wrong there, that would be awesome too.)
When I load the file, T ends up being a strcuture with 1 field that holds my two columns of data. I've settled on just extracting the field. But the field has the same name as the file, so its name has to change with every loop. I've shown this as 'mic2_%n' which, frankly, I made up. So you see the problem. What's the solution? Please and Thank you.
Edit: Just realised extractfield just give me a cell that contains my data. What's the magic function that will just give me the data array straight up?
clear
sum= zeros(1,6);
for n=1:6
filename = sprintf('mic2_%d.mat',n);
T = load(filename);
S = extractfield(T,'mic2_%n');
% T = load(filename);
% S = struct2array(T);
% fid = fopen(filename, 'r');
% S = fread(fid,[1 2]);
x= S(:,1);
y= S(:,2);
Length = size(S);
for i = 1:Length
x(i)=(x(i)-x(i+1));
y(i)=(y(i)-y(i+1));
end
sum(1:n) = x(i)^2+y(i)^2;
end
Print sum
Ensemble_Average = mean(sum);
Print Ensemble_Average
D = Ensemble_Average/4*tau;
Print D
댓글 수: 2
James Tursa
2019년 5월 15일
So, you saved the data under different numbered names in each file, right? That was your problem from the beginning. You should have used consistent naming in the beginning and then your downstream coding would be easier. Can you change the code that creates the files?
채택된 답변
madhan ravi
2019년 5월 15일
편집: madhan ravi
2019년 5월 15일
Note: Don‘t ever name a variable sum it would hinder the inbuilt function sum(). Also size(s) should be length(s).
S = T.(sprintf('mic2_%d',n)); % replace the line with exctractfield with this line
댓글 수: 2
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Entering Commands에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!