Loading in excel data with loop and plotting

I took 2 pieces of code and tried to put them together, but it did not work.
When I load in data like this:
S=struct;
S.A600= xlsread(filename,'0.600');
S.A601= xlsread(filename,'0.601');
etc.
and
then do this:
fn = fieldnames(S);
for k = 1:length(fn)
thisS = S.(fn{k});
x = thisS(:, 1);
y = thisS(:, 2);
fprintf('Printing field #%d.\n', k);
semilogy(x, y,'-o');
hold on
drawnow;
end
Everything works fine, namely because fn is defined correctly. Here, fn is 20x1.
But when I try to load data in with a loop and do this:
filename = 'C:\PATH\variable_analysis.xlsx';
S=struct;
for n=20:-1:1
A= xlsread(filename,sprintf('0.6%02d',n));
S(n).data=A;
end
fn = fieldnames(S);
for k = 1:length(fn)
thisS = S.(fn{k});
x = thisS(:, 1);
y = thisS(:, 2);
fprintf('Printing field #%d.\n', k);
semilogy(x, y,'-o');
hold on
drawnow;
end
grid on;
fn is only a 1x1 cell, so only 1 dataset is plotted.
I know I am making an obvious error somewhere, but I cannot find it.

6 comentarios

Image Analyst
Image Analyst el 12 de Nov. de 2018
You forgot to attach 'C:\PATH\variable_analysis.xlsx'.
Benjamin
Benjamin el 12 de Nov. de 2018
I just attached an example file
Bob Thompson
Bob Thompson el 12 de Nov. de 2018
I could be wrong, but I suspect that the issues is that when you conduct the second portion, you are only defining one field of S, the 'data' field. So rather than defining fn as fn = fieldnames(S), just use the different elements of S: fn = size(S,1). Then replace S.(fn{k}) with S(fn(k)).data.
Again, I could be wrong.
Benjamin
Benjamin el 12 de Nov. de 2018
Editada: Benjamin el 12 de Nov. de 2018
Thanks for the effort, but still did not solve it. fn = size(S,1) just produces fn = 1, so it still only plots one dataset. S is a 1x20 struct, with 18x49 arrays.
Bob Thompson
Bob Thompson el 12 de Nov. de 2018
Editada: Bob Thompson el 12 de Nov. de 2018
If S is 1x20 then you need to use fin = size(S,2). In the size command the number indicates which dimension you're looking at.
Also, now that I'm looking at it again. You don't actually need fn at all. Just replace the loop index with 'for k = 1:size(S,2)' and then use S(k).data in the loop.
Benjamin
Benjamin el 12 de Nov. de 2018
Editada: Benjamin el 12 de Nov. de 2018
wow, thanks, that seems to work!

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 12 de Nov. de 2018

Editada:

el 12 de Nov. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by