creating subplot from function

8 visualizzazioni (ultimi 30 giorni)
Benjamin
Benjamin il 7 Nov 2018
Modificato: Benjamin il 7 Nov 2018
I have some code, generally looks like this:
x='dr_0.01.txt';
foo(x);
function y = foo(fname)
Do stuff
end
Ultimately, the function creates a figure. How can I load in other files with the x variable, run foo(x), and put each figure created from each call to function f into a subplot that is 2x2? So I want to load in 4 files, and call the function on all 4 files. Then create a subplot that contains all 4.

Risposte (1)

Chad Greene
Chad Greene il 7 Nov 2018
Looks like instead of x you meant to call that variable fname? If so, something like this:
fname = {'fname1.txt','fname2.txt','fname3.txt','fname4.txt'};
function y = foo(fname)
% Load and plot each dataset:
for k = 1:length(fname)
D = importdata(fname{k});
subplot(2,2,k)
y(k) = plot(D(:,1),D(:,2))
end
end
  1 Commento
Benjamin
Benjamin il 7 Nov 2018
Modificato: Benjamin il 7 Nov 2018
Any reason why this code does not produce all 4 graphs on the subplot? It just produces the one at the top left.
fname = {'dr_0.01.txt','dr_0.005.txt','dr_0.001.txt','dr_0.0001.txt'};
delimiterIn = ' ';
headerlinesIn = 5;
foo(fname);
function y = foo(fname)
% Load and plot each dataset:
for k = 1:length(fname)
matrix = importdata(fname{k});
A = matrix.data;
%Define the number of distinct isotherms
temp_ids = sum(A(:) == 0.2);
%Define the number of density points sampled
density_ids = length(A)/temp_ids;
%Grab density matrix
density = A((1:density_ids),1);
%Grab temperature matrix
pressure = A(:,3);
%Reshape pressure matrix so it has one column for each temperature
%(isotherm), rather than just a single long column
pressure = reshape(pressure,[density_ids,temp_ids]);
%Differentiate
[~,dPdD] = gradient(pressure, mean(diff(density)));
[~,ddPddD] = gradient(dPdD, mean(diff(density)));
subplot(2,2,k)
y(k) = plot(density, ddPddD);
grid on;
ylim([-0.2 0.4])
xlim([0.4 0.8])
xlabel('\rho (g/cm^3)');
ylabel('\partial^2p/\partial\rho^2')
end
end
It outputs a subplot, but only the top left graph shows up. Note that density is an a single column array and ddPddD is several columns and rows. It gives this error:
Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.
Error in prac>foo (line 40)
y(k) = plot(density, ddPddD);
Error in prac (line 9)
foo(fname);

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by