Plotting of graph with multiple curve

for a function with 2-unknown parameter, I wrote this code below. Is there any way it can be improved?
clear all
q=.9;
x = linspace(0,10);
for i1 = 1:4
b = input('input the shape parameter beta b');
f = zeros(1,4);
for ii = 1:length(x)
f(ii) =b*q^2/(q+1)*(1+b*x(ii))*exp(-b*q*x(ii));
end
plot(x,f,'linewidth',2)
hold on
end
legend('\beta=.05','\beta=.02','\beta=.5')
hold off
Thank for helping to learn MATLAB Package.

 Accepted Answer

I am not certain what you want to do. You already appear to have defined three different values for ‘beta’ (as defined in your legend call), so just use those rather than having them input from the Command Window.
Beyond that, you can eliminate the inner ‘ii’ loop entirely with element-wise operations (replace ‘*’ with ‘.*’).
q = 0.9;
x = linspace(0,10);
beta = [0.05; 0.2; 0.5];
for i1 = 1:3
b = beta(i1);
f = b*q^2/(q+1)*(1+b*x).*exp(-b*q*x);
plot(x,f,'linewidth',2)
hold on
end
legend('\beta=.05','\beta=.02','\beta=.5')
hold off
You can eliminate the outer loop as well if you are get (or define) all the ‘beta’ values first:
q = 0.9;
x = linspace(0,10);
beta = [0.05; 0.2; 0.5];
[X,B] = meshgrid(x, beta);
f = B.*q.^2./(q+1).*(1+B.*X).*exp(-B.*q.*X);
plot(x,f,'linewidth',2)
hold on
legend('\beta=.05','\beta=.02','\beta=.5')
hold off
See the documentation on Array vs. Matrix Operations (link) for more information on element-wise operations. See the documentation on meshgrid to understand what it does and how to use it.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!