필터 지우기
필터 지우기

creating subplot from function

조회 수: 2 (최근 30일)
Benjamin
Benjamin 2018년 11월 7일
편집: Benjamin 2018년 11월 7일
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.

답변 (1개)

Chad Greene
Chad Greene 2018년 11월 7일
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
Benjamin
Benjamin 2018년 11월 7일
편집: Benjamin 2018년 11월 7일
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);

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by