Plot while changing different parameters matlab - matlab

I've written the following code for pricing options in matlab:
function call=CallBinomial(S,E,T,r,sigma)
S=100;
E=90;
T=2;
r=0.03;
sigma=0.2;
n=50;
dt=T/n;1
u=exp(sigma*sqrt(dt)+(r+0.5*sigma^2)*dt); d=1/u;
disf=exp(-r*dt);
p=0.5;
X=zeros(n+1,n+1);
for k=1:(n+1)
X(n+1,k)=max(S*u^(k-1)*d^(n-k+1)-E,0);
end
for m=n:-1:1
for k=1:m
X(m,k)=disf*( p*X(m+1,k+1) + (1-p)*X(m+1,k) );
end
end
call=X(1,1)
I want to plot a graph of the changing value of the call as I vary different parameters S, r, sigma but i'm unsure of how to do this.

Here is a simle example where you can change the parameters to plot inside a for loop:
for i = 1:.1:2
plot(i,i); % plot different things
axis([0 3 0 3]); % forces a constant size of window
pause(.2); % pauses before the next plot
end

Related

Using Trapezium Rule on any function and show a graph

I have successfully managed to create a code in which I can estimate the area beneath the curve using the Trapezium rule. What I am struggling to do is plot the corresponding graph. I've used x^2 as the example and in the image I've attached a=-5, b=5 and n=3. And the original x^2 graph is not coming up but rather a merge between the blue and green lines. Can someone help fix this? Thank you.
Figure 1
% Trapezium Rule
f=#H; % Input Function
a=input('Enter lower limit a: ');
b=input('Enter upper limit b: ');
n=input('Enter the no. of interval: ');
h=(b-a)/n;
sum=0;
% Sum of f(x_1) to f(x_n+1)
for k=1:1:n+1
x(k)=a+k*h;
y(k)=f(x(k));
sum=sum+y(k);
end
hold on
plot(x, y,'bo-');
% drawing of the function
plot([x(1:end); x(1:end)], [zeros(1,length(y)); y(1:end)], 'r-');
% vertical lines from the points
plot([x(1:end-1); x(2:end)], [y(1:end-1) ; y(1: end)], 'g--');
% Meant to be forming a trapizium
hold off
answer = (h*0.5)*(sum);
% answer=h/2*(f(a)+f(b)+2*sum);
fprintf('\n The value of integration is %f',answer);
function y = H(x)
y = x.^2;
end
Your green line does not go from the same value to the same value! It foes from one to the next. You forgot that.
% the only reason you do -1 is so the last y can go to the end! The same as x
plot([x(1:end-1); x(2:end)], [y(1:end-1) ; y(2: end)], 'g--');

How to choose a specific value from a loop to be plotted against a range of values?

I cannot think of the proper wording for this, but I am trying to have my code run a loop that will input a value of X into an initial condition variable. This variable is then inputted into the heat equation to be plotted. From the code I want to choose a value which is at X(i=51) and plot it as T(x,T1). As i said before I don't know the proper wording to search for a possible solution. Any advice would be great!
clear;
clc;
% initialize given variables
A= 0.25;
L= pi;
Nx=101; Nt=10^(-4);
dx=L/(Nx-1);
T1=zeros(1,Nx);
x=linspace(0, L, Nx); %x distance
%Initial condition
%T1 will be the "new" T value and To will be the old
T1= x.*(pi-x);
%For plotting, time starts at 0.
t=0;
for n=1:50
To=T1;
t=t+1;
for i=2:Nx-1
T1(i)=To(i)+Nt *A*((To(i+1)-2*To(i)+To(i-1))/(dx^2))+ sin(5*x(i));
end
%B.C given than # T(0,t) & T(L,t) = 0
T1(1)=0; T1(end)=0;
figure(1)
plot(x,T1); set(gca, 'ylim',[-110 110]);
ylabel('Temperature along the Rod');
xlabel('Location on the Rod of length Pi');
title(sprintf('Time = %f seconds', t));
pause(0.001);
end
The expected out put that I want to plot is plot(x(i=51),T1) which would show an image just like this. For this plot I ran my code and altered i to =50:51 to get the needed values for the heat equation. I am trying to have this be plotted in the code shown and not have to rewrite my code over and over to get different plots because I change values such as i or time ect...
You want to plot a consistent value of x, specifically x(51), for every n.
This can be done a couple of ways
First, as individual points with hold on:
for n = 1:50
% ... calculation ...
hold on
plot( x(51), T1(51), '.' );
hold off
end
You could update the plot, this will be quicker to compute and has the advantage of showing a line plot
x_51 = NaN( 50, 1 );
T1_51 = NaN( 50, 1 );
p = plot( [], [] );
for n = 1:50
% ... calculation ...
x_51(n) = x(51);
T1_51(n) = T1(51);
set( p, 'XData', x_51, 'YData', T1_51 );
end

Continuous plot while plotting inside a loop in MATLAB

I am trying to plot variables dynamically in MATLAB. I have an array (set of states) that needs to be plotted with time. I tried plot(time,theta), where theta is a 1*5 array. With this command, I get an error saying that theta should be a scalar because time is a scalar. I then tried using for-loop to plot(time,theta(i)). The problem with this is that I get data points at discrete time intervals on my plot. However I need a continuous plot. I wonder how this can be done.
You need to use hold on when plotting.
For example:
time = 1;
theta = [1:100];
figure
for i=1:100
plot(time, theta(i),'r.')
hold on %--> Keeps the previous data in your plot
time = time + 1;
end
Let's see if I get this straight. Time is updated at every step, and theta are five different variables that also get updated. This should work for you:
% Use your own time variable
time = 1:100;
figure; hold on;
h = cell(5,1); % Handles of animated lines
colors = 'rgbkm'; % Colors of lines
for t = time
theta = randn(5,1);
if isempty(h{1})
% Initialize plot
for k = 1 : 5
h{k} = animatedline(t , theta(k) , 'LineStyle' , '-' , 'Color' , colors(k));
end
else
% Update plot with new data
for k = 1 : 5
addpoints(h{k}, t , theta(k));
end
end
% Update plot
drawnow
end
The object animatedline was introduced in R2014b. You can still do something similar with a conventional plot and updating the XData and YData properties of the lines at each loop.

Reset ColorOrder index for plotting in Matlab / Octave

I have matrices x1, x2, ... containing variable number of row vectors.
I do successive plots
figure
hold all % or hold on
plot(x1')
plot(x2')
plot(x3')
Matlab or octave normally iterates through ColorOrder and plot each line in different color. But I want each plot command to start again with the first color in colororder, so in default case the first vector from matrix should be blue, second in green, third in red etc.
Unfortunately I cannot find any property related to the color index niether another method to reset it.
Starting from R2014b there's a simple way to restart your color order.
Insert this line every time you need to reset the color order.
set(gca,'ColorOrderIndex',1)
or
ax = gca;
ax.ColorOrderIndex = 1;
see:
http://au.mathworks.com/help/matlab/graphics_transition/why-are-plot-lines-different-colors.html
You can shift the original ColorOrder in current axes so that the new plot starts from the same color:
h=plot(x1');
set(gca, 'ColorOrder', circshift(get(gca, 'ColorOrder'), numel(h)))
plot(x2');
You can wrap it in a function:
function h=plotc(X, varargin)
h=plot(X, varargin{:});
set(gca, 'ColorOrder', circshift(get(gca, 'ColorOrder'), numel(h)));
if nargout==0,
clear h
end
end
and call
hold all
plotc(x1')
plotc(x2')
plotc(x3')
Define a function that intercepts the call to plot and sets 'ColorOrderIndex' to 1 before doing the actual plot.
function plot(varargin)
if strcmp(class(varargin{1}), 'matlab.graphics.axis.Axes')
h = varargin{1}; %// axes are specified
else
h = gca; %// axes are not specified: use current axes
end
set(h, 'ColorOrderIndex', 1) %// reset color index
builtin('plot', (varargin{:})) %// call builtin plot function
I have tested this in Matlab R2014b.
I found a link where a guy eventually solves this. He uses this code:
t = linspace(0,1,lineCount)';
s = 1/2 + zeros(lineCount,1);
v = 0.8*ones(lineCount,1);
lineColors = colormap(squeeze(hsv2rgb(t,s,v)))
ax=gca
ax.ColorOrder = lineColors;
Which should work for you assuming each of your matrices has the same number of lines. If they don't, then I have a feeling you're going to have to loop and plot each line separately using lineColors above to specify an RBG triple for the 'Color' linespec property of plot. So you could maybe use a function like this:
function h = plot_colors(X, lineCount, varargin)
%// For more control - move these four lines outside of the function and make replace lineCount as a parameter with lineColors
t = linspace(0,1,lineCount)'; %//'
s = 1/2 + zeros(lineCount,1);
v = 0.8*ones(lineCount,1);
lineColors = colormap(squeeze(hsv2rgb(t,s,v)));
for row = 1:size(X,1)
h = plot(X(row, :), 'Color', lineColors(row,:), varargin{:}); %// Assuming I've remembered how to use it correctly, varargin should mean you can still pass in all the normal plot parameters like line width and '-' etc
hold on;
end
end
where lineCount is the largest number of lines amongst your x matrices
If you want a slightly hacky, minimal lines-of-code approach perhaps you could plot an appropriate number of (0,0) dots at the end of each matrix plot to nudge your colourorder back to the beginning - it's like Mohsen Nosratinia's solution but less elegant...
Assuming there are seven colours to cycle through like in matlab you could do something like this
% number of colours in ColorOrder
nco = 7;
% plot matrix 1
plot(x1');
% work out how many empty plots are needed and plot them
nep = nco - mod(size(x1,1), nco); plot(zeros(nep,nep));
% plot matrix 2
plot(x2');
...
% cover up the coloured dots with a black one at the end
plot(0,0,'k');

Get access to the default LineStyleOrder and ColorOrder arrays in MATLAB

Quick "convenience" question for MATLAB users. I am looping over a plot command, passing it different data to plot each time. The data happens to be generated from a function call, which upon each iteration is passed a different parameter value. To plot everything on the same axis I am using the 'hold' function. Unfortunately this doesn't auto cycle through the available ColorOrder and/or LineStyleOrder plot parameters, so every line plotted has the same style on every iteration.
for i=1:nLines
[x_data y_data]=get_xy_data(param1(i),param2(i))
plot(x_data,y_data)
end
Every line plotted will be the default blue line style.
The obvious solution is to generate up front a cell array of the various line styles, and colors as in:
line_styles={'-','--','-*'}; %...etc
colors=colormap(jet(nLines));
then access each of those on every iteration. What I want is access to the default colors which will be generated from ColorOrder, and the default line cycling, which comes from LineStyleOrder. If I try something like:
get(gca,'LineStyleOrder')
This only returns the styles used in that axis (I've only tested this on an axis defined with one of the styles, but point is, it doesn't give me all possible linestyles). Help appreciated, thanks!
EDIT: Let me be more specific in what I am looking for.
figure; hold on;
for i=1:nLines
[xdata, ydata]=get_data(p1(i),p2(i)) % call some function to return x,y data
plot(xdata,ydata) % on i=1, default blue line
% function which tells matlab to get/set the next linestyle, color combination
nextStyle()
end
If this doesn't exist, it wouldn't be too hard to write it, but I thought I'd ask first before reinventing the wheel.
You may be interested in setting the default properties of DefaultAxesLineStyleOrder and DefaultAxesColorOrder.
The plots (style and color) will first loop through the newly defined colors and then changed the line style. In a successive plot loop, using hold all will "hold the graph and the current line color and line style so that subsequent plotting commands do not reset the ColorOrder and LineStyleOrder" (see the matlab doc). Both examples produce identical results.
%default properties (line style and color)
set(0,'DefaultAxesLineStyleOrder',{'--','-',':'})
set(0,'DefaultAxesColorOrder', summer(4))
figure('Color','w');
%example plot 1 (concurrent plots)
subplot(1,2,1);
yvals = [1:50;1:50]
plot(yvals, 'LineWidth', 2)
axis([1 2 0 size(yvals,2)+1 ]);
title('concurrent plot','FontSize',16);
%example plot 2 (iterative plots)
subplot(1,2,2);
for ii = 1:50
plot(yvals(:,ii), 'LineWidth', 2);
hold all;
end
axis([1 2 0 size(yvals,2)+1 ]);
title('successive plot','FontSize',16);
The results are
It looks like #Luis Mendo was not that wrong!
You can use hold all. That automatically sets different colors and linestyles for each plot.
You could set the line style and color directly for each line. Here's an example:
figure
hold on
nLines = 12;
line_styles={'-','--','-.'};
colors= hsv(nLines);
indexColors = 1;
indexLines = 1;
for i=1:nLines
xData = 1:10;
yData = rand(1,10);
h = plot(xData,yData);
ls = line_styles{indexLines};
c = colors(indexColors,:);
set(h,'color',c)
set(h,'LineStyle',ls)
if indexColors < length(colors)
indexColors = indexColors + 1;
else
indexColors = 1;
end
if indexLines < length(line_styles)
indexLines = indexLines + 1;
else
indexLines = 1;
end
end