How to plot for loop results in matlab? - matlab

I am calculating the absolute error of a summation compared to an integral (summation answer - integral answer):
integral of e^x from 0 to 1, compared to (1/n)*summation(e^rand()) from i = 1 to n.
I have to plot the error vs n in matlab. I can't wrap my head around how to do this. I am able to calculate the error from 1 to an arbitrary number like 50 by using a for loop from 1 to 50. But, how would I plot this? I would need to do multiple summations to different values of n correct?

So what you want to do is calculate the area with the integral and the error function at the same time and store them in an array:
maxLevel = 50;
integral = zeros(maxLevel, 1);
summation = zeros(maxLevel, 1);
for i = 1:maxLevel
integral(i) = integralFunction(i);
summation(i) = summationFunction(i);
end
Then you can plot like this:
plot(1:length(integral), integral, 'r');
hold on;
plot(1:length(summation), summation, 'g');

Related

Solving Least square using MATLAB

Assume we want to determine the coefficients of a polynomial equation that is approximating the tangent function between 0 to 1, as follow:
-A is m×n vandermonde matrix. The entries are populated using m value between 0 to 11(given as input).
-The corresponding vector b is calculated using tangent function.
-x is calculated by typing x= A\b in MATLAB.
Now, using MATLAB, the computed x are subsittued in Ax. The result is plotted and it is pretty close to tangent function. But if I use polyval function of n−1 degree (in MATLAB) to calculate b, the resulting plot is significantly different from the original b. I cannot understand the reason for such a significant difference between the results of these two methods.
Here is the code:
clear all;
format long;
m = 60;
n = 11;
t = linspace(0,1,m);
A= fliplr(vander(t));
A=A(:,1:n);
b=tan(t');
x= A\b;
y=polyval(x, t);
plot(t,y,'r')
y2= A*x
hold on;
plot(t,y2,'g.');
hold on;
plot(t,tan(t),'--b');
Any insight would be appreciated. Thank you.
After A= fliplr(vander(t)) the A matrix is equal to
1 t(1) t(1)^2 ...
1 t(2) t(2)^2 ...
...
1 t(m) t(m)^2 ...
It is not correct because polyval accepts the coefficients in descending powers. You don't need to flip the columns of A:
A= vander(t);
A= A(:,end-n+1:end);

MATLAB: polyval function graphs multiple lines for N>1

I am trying to graph a polynomial function using the following code:
y = polyfit(P,C,3);
Line = polyval(y, P);
y =
2.0372e-14 -4.0614e-09 0.0002 2.6060
figure
plot(P,C,'.')
hold on
plot(P, Line, '-')
legend('Observations','y')
axis([0 90000 0 10])
The problem is, it produces multiple lines like this:
This problem does not occur if I set N = 1 or y = polyfit(P,C,1);. In that case I get a proper graph with one line:
How can I graph just 1 line for N = 3?
Here is an Excel version of what I am trying to produce in Matlab:
This is because your observations P are in an arbitrary order: Matlab is going from point to point in that order. You don't actually need to plot the fitted curve at each value P, you just need to plot the fitted curve over the range of P:
Pfitted = linspace(min(P),max(P),1000) % Generate 1000 equally spaced points
Cfitted = polyval(y,Pfitted) % Fit to these points
plot(Pfitted,Cfitted,'-')

Why MATLAB is only plotting maximum three functions

I'm trying to plot multiple Fourier series approximations for the function f(x)=(x^2-pi^2)^3, but for some reason my MATLAB will only plot maximum two of the approximations (along with the original f). How can I get it to plot 4 or more? My code for the series is
function [Y]=fourier(X)
N=input('enter the value of N:' )
SN=-16*pi^6/35;
for n=1:N
SN=SN+96*(-1)^n/n^5*(15/n-pi^2).*cos(n*X);
end
Y=SN;
and using
plot(X,Y1,'b',X,Y2,'r',X,Y3,'m',X,Y4,'g')
(where Yi=fourier(X), X=[-pi:0.01:pi] are the various approximations for different N) isn't working; nor is plotting them one by one.
Many thanks in advance for any help that anyone can offer - as you may have noticed I'm a very amateur programmer!!
I have no problems.
I modified your fourier function to accept input N:
function Y = fourier(X,N)
SN = -16*pi^6/35;
for n = 1:N
SN = SN+96*(-1)^n/n^5*(15/n-pi^2).*cos(n*X);
end
Y = SN;
Then, I get the 4 lines:
X = (-pi:0.01:pi)';
Y = [fourier(X,1), fourier(X,2), fourier(X,3), fourier(X,4)];
plot(X,Y)
legend 1 2 3 4
set(gca, 'Xlim',[-3.3, -2.3], 'Ylim',[-60,79])

evaluating a self made function for a cector and then plotting in matlab

i have created a function that represents a triangle sign.
this function does not work on vectors. i want to evaluate a vector x:
x=[-2:0.01:2]
and save the answer in vector y, for this purpose i came up with the following code:
for i=1:400, y(i) = triangle(x(i))
after i got the ans i plotted is using plot. in this case it worked ok but i am interested on observing the influence of time shifting and shrinking so when i try to use lets say:
for i=1:200, y(i) = triangle(x(2*i))
i get a vector y not the same length as vector x and i cant even plot them... is there any easy way to achieve it? and how should i plot the answer?
here is my function:
function [ out1 ] = triangle( input1 )
if abs(input1) < 1,
out1 = 1 - abs(input1);
else
out1 = 0;
end
end
y is a different length in each for loop because each loop iterated a different number of times. In the example below, I use the same for loops and plot y2 with the corresponding values of x. i is already defined in matlab so I've changed it to t in the example below.
clear all
x=[-2:0.01:2];
for t=1:400
y(t) = triangle(x(t));
end
for t=1:200
y2(t) = triangle(x(2*t));
end
Or, if you want to see y2 plotted over the same range you can increase the size of x:
clear all
x=[-2:0.01:8];
for t=1:400
y(t) = triangle(x(t));
end
for t=1:400
y2(t) = triangle(x(2*t));
end
plot(x(1:length(y)),y,'r')
hold on
plot(x(1:length(y2)),y2,'b')

Can someone explain how to graph this sum in MATLAB using contourf?

I'm going to start off by stating that, yes, this is homework (my first homework question on stackoverflow!). But I don't want you to solve it for me, I just want some guidance!
The equation in question is this:
I'm told to take N = 50, phi1 = 300, phi2 = 400, 0<=x<=1, and 0<=y<=1, and to let x and y be vectors of 100 equally spaced points, including the end points.
So the first thing I did was set those variables, and used x = linspace(0,1) and y = linspace(0,1) to make the correct vectors.
The question is Write a MATLAB script file called potential.m which calculates phi(x,y) and makes a filled contour plot versus x and y using the built-in function contourf (see the help command in MATLAB for examples). Make sure the figure is labeled properly. (Hint: the top and bottom portions of your domain should be hotter at about 400 degrees versus the left and right sides which should be at 300 degrees).
However, previously, I've calculated phi using either x or y as a constant. How am I supposed to calculate it where both are variables? Do I hold x steady, while running through every number in the vector of y, assigning that to a matrix, incrementing x to the next number in its vector after running through every value of y again and again? And then doing the same process, but slowly incrementing y instead?
If so, I've been using a loop that increments to the next row every time it loops through all 100 values. If I did it that way, I would end up with a massive matrix that has 200 rows and 100 columns. How would I use that in the linspace function?
If that's correct, this is how I'm finding my matrix:
clear
clc
format compact
x = linspace(0,1);
y = linspace(0,1);
N = 50;
phi1 = 300;
phi2 = 400;
phi = 0;
sum = 0;
for j = 1:100
for i = 1:100
for n = 1:N
sum = sum + ((2/(n*pi))*(((phi2-phi1)*(cos(n*pi)-1))/((exp(n*pi))-(exp(-n*pi))))*((1-(exp(-n*pi)))*(exp(n*pi*y(i)))+((exp(n*pi))-1)*(exp(-n*pi*y(i))))*sin(n*pi*x(j)));
end
phi(j,i) = phi1 - sum;
end
end
for j = 1:100
for i = 1:100
for n = 1:N
sum = sum + ((2/(n*pi))*(((phi2-phi1)*(cos(n*pi)-1))/((exp(n*pi))-(exp(-n*pi))))*((1-(exp(-n*pi)))*(exp(n*pi*y(j)))+((exp(n*pi))-1)*(exp(-n*pi*y(j))))*sin(n*pi*x(i)));
end
phi(j+100,i) = phi1 - sum;
end
end
This is the definition of contourf. I think I have to use contourf(X,Y,Z):
contourf(X,Y,Z), contourf(X,Y,Z,n), and contourf(X,Y,Z,v) draw filled contour plots of Z using X and Y to determine the x- and y-axis limits. When X and Y are matrices, they must be the same size as Z and must be monotonically increasing.
Here is the new code:
N = 50;
phi1 = 300;
phi2 = 400;
[x, y, n] = meshgrid(linspace(0,1),linspace(0,1),1:N)
f = phi1-((2./(n.*pi)).*(((phi2-phi1).*(cos(n.*pi)-1))./((exp(n.*pi))-(exp(-n.*pi)))).*((1-(exp(-1.*n.*pi))).*(exp(n.*pi.*y))+((exp(n.*pi))-1).*(exp(-1.*n.*pi.*y))).*sin(n.*pi.*x));
g = sum(f,3);
[x1,y1] = meshgrid(linspace(0,1),linspace(0,1));
contourf(x1,y1,g)
Vectorize the code. For example you can write f(x,y,n) with:
[x y n] = meshgrid(-1:0.1:1,-1:0.1:1,1:10);
f=exp(x.^2-y.^2).*n ;
f is a 3D matrix now just sum over the right dimension...
g=sum(f,3);
in order to use contourf, we'll take only the 2D part of x,y:
[x1 y1] = meshgrid(-1:0.1:1,-1:0.1:1);
contourf(x1,y1,g)
The reason your code takes so long to calculate the phi matrix is that you didn't pre-allocate the array. The error about size happens because phi is not 100x100. But instead of fixing those things, there's an even better way...
MATLAB is a MATrix LABoratory so this type of equation is pretty easy to compute using matrix operations. Hints:
Instead of looping over the values, rows, or columns of x and y, construct matrices to represent all the possible input combinations. Check out meshgrid for this.
You're still going to need a loop to sum over n = 1:N. But for each value of n, you can evaluate your equation for all x's and y's at once (using the matrices from hint 1). The key to making this work is using element-by-element operators, such as .* and ./.
Using matrix operations like this is The Matlab Way. Learn it and love it. (And get frustrated when using most other languages that don't have them.)
Good luck with your homework!