user3589557
user3589557

Reputation: 147

Iteration and subplot

I would like to plot 5 subplots with a different value of x each time (1 to 5). Rather than repeating the code 5 times (each time changing x) I thought it would be more elegant to use a for loop to plot each subplot. However, I cannot get the code to work.

On a further note, when I plot the five plots manually, for some reason the axes labels only appear on the Y axis. How can I get them to appear on all axes?

% constants
a=30;
b=0.5;

% parameters
x=1:1:5 ;
e1 = 0:10:10000; 
e2 = 0:10:10000; 

[e1,e2]=meshgrid(e1,e2);

% plots

t(x)=(a.^(6.*x)/factorial(6.*x))*...
    (exp(-b*x.*e2));

u(x)=((a.^(a-(6.*x)))/factorial(a-(6.*x)))*...
    exp(-b*(a-(6.*x)).*e1);

p(x)=t(x)./(t(x)+u(x));

%FIGURES:

for i=length(x)

    figure
    subplot(3,2,i);
    mesh(e1,e2,p(i));
    title('X=i');
    axis([1 10000 1 1000 10^-300 1])
    xlabel('e1');
    ylabel('e2');
    zlabel('p');

end

Upvotes: 1

Views: 541

Answers (1)

Dani Gehtdichnixan
Dani Gehtdichnixan

Reputation: 1285

Okay, your code had several bugs. Here is one that works:

% constants
a=30;
b=0.5;

% parameters
x=1:1:5 ;
e1 = 0:10:10000; 
e2 = 0:10:10000; 

[e1,e2]=meshgrid(e1,e2);

% plots

t=@(x)(a.^(6.*x)./factorial(6.*x))*...
    (exp(-b*x.*e2));

u=@(x)((a.^(a-(6.*x)))/factorial(a-(6.*x)))*...
    exp(-b*(a-(6.*x)).*e1);

p=@(x)t(x)./(t(x)+u(x));

%FIGURES:
figure
for i=x


    subplot(3,2,i);
    mesh(e1,e2,p(i));
    title(['X=',int2str(i)]);
    axis([1 10000 1 1000 10^-300 1])
    xlabel('e1');
    ylabel('e2');
    zlabel('p');

end

The issues were:

  1. Anonymous functions are defined by t=@(x)([function here]) not t(x)=[function here]
  2. You need to iterate over all the elements of x so the for loop needs to be for i=x
  3. The figure statement needs to be outside of the for loop, otherwise there will be a new figure at every iteration.
  4. title() does not parse the string for variables.

Hope that helped.

Upvotes: 0

Related Questions