MATLAB Answers


creating subplot from function

Asked by Benjamin on 7 Nov 2018
Latest activity Edited by Benjamin on 7 Nov 2018
I have some code, generally looks like this:
function y = foo(fname)
Do stuff
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.


Sign in to comment.

1 Answer

Answer by Chad Greene
on 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});
y(k) = plot(D(:,1),D(:,2))

  1 Comment

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;
function y = foo(fname)
% Load and plot each dataset:
for k = 1:length(fname)
matrix = importdata(fname{k});
A =;
%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]);
[~,dPdD] = gradient(pressure, mean(diff(density)));
[~,ddPddD] = gradient(dPdD, mean(diff(density)));
y(k) = plot(density, ddPddD);
grid on;
ylim([-0.2 0.4])
xlim([0.4 0.8])
xlabel('\rho (g/cm^3)');
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)

Sign in to comment.