How to extract a field from a structure in a 'for loop', so that it would behave like an array?

7 visualizzazioni (ultimi 30 giorni)
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 Commenti
James Tursa
James Tursa il 15 Mag 2019
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?
pistachionut
pistachionut il 15 Mag 2019
With barely any experience, I was just dumping data from excel into matlab. I thought I was naming the file not the fields inside it. TBH I have no idea what's going on there.

Accedi per commentare.

Risposta accettata

madhan ravi
madhan ravi il 15 Mag 2019
Modificato: madhan ravi il 15 Mag 2019
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

Più risposte (0)

Categorie

Scopri di più su Entering Commands in Help Center e File Exchange

Prodotti


Release

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by