How to subplot two or more multiple-plots created by different loops

4 次查看(过去 30 天)
Hi,
I am trying to create a subplot(2,1), but I do not know how I should use this function when I have two plots created by differents loops. Here the code without subplot:
clear all; clc;
n=input('The value of n is:');
k=100;
X1=linspace(-20,20,k);
X2=linspace(-1,1,k);
M=zeros(n,k);
N=zeros(n,k);
figure(); hold on
for i = 1:n
plot(X1,besselj(i,X1));
legendInfo{i} = ['n = ' num2str(i)];
end
legend(legendInfo)
title('Bessel')
xlabel('X')
ylabel('Y')
hold off
figure(); hold on
for i = 1:n
plot(X2,legendre(i,X2));
legendInfo{i} = ['n = ' num2str(i)];
end
legend(legendInfo)
title('Legendre')
xlabel('X')
ylabel('Y')
hold off
My question is: Where I put the subplot function? I have tried and the only thing that I get is error.
Thank you very much.
Have a nice day.

回答(1 个)

Aditya
Aditya 2025-5-28
Hi Jaime,
To create subplots for multiple plots generated by different loops, follow these steps:
  1. Use "subplot(2,1,1)" before the first loop to place the Bessel function plot in the first row.
  2. Use "subplot(2,1,2)" before the second loop to place the Legendre function plot in the second row.
  3. Don't call "figure()" before each for loop.
Here is how the updated code looks like:
clear all; clc;
n = input('The value of n is:');
k = 100;
X1 = linspace(-20,20,k);
X2 = linspace(-1,1,k);
M = zeros(n,k);
N = zeros(n,k);
figure; % Create a single figure for subplots
% First subplot for Bessel function
subplot(2,1,1); hold on;
legendInfo = cell(n,1);
for i = 1:n
plot(X1, besselj(i, X1));
legendInfo{i} = ['n = ' num2str(i)];
end
legend(legendInfo);
title('Bessel Function');
xlabel('X');
ylabel('Y');
hold off;
% Second subplot for Legendre function
subplot(2,1,2); hold on;
legendInfo = cell(n,1);
for i = 1:n
plot(X2, legendre(i, X2));
legendInfo{i} = ['n = ' num2str(i)];
end
legend(legendInfo);
title('Legendre Function');
xlabel('X');
ylabel('Y');
hold off;
For more details on the subplot function refer to the below MATLAB documentation:
I hope this helps!

类别

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