How do I plot the sum of two discrete time signals? - matlab

I have x[n] = {1,2,2,1,4} and −1 ≤ n ≤ 5
How do I plot y[n] = x[n] + y[n-1]?
I am new to matlab, and am not sure how to go about this.

This question does not seem well posed. Your vector for n in your first statement makes no sense (to me) in the context of your second statement.
If we ignore the first statement for n, your second statement appears to tell us how to build up a new value of y given x and given the previous previous of y. That's fine. You can easily solve for y with a for loop.
x = [1,2,2,1,4]; % this is your given input data
y = []; % this is your output
for I=1:length(x) % loop over each value of x
if (I==1) % the first time through is a special case
%assume that the previous value of y is zero
y(I) = x(I);
else
%your given equation
y(I) = x(I) + y(I-1);
end
end
y(:) %display y to the screen

The function y[n] = x[n] + y[n-1] is the sum (or discrete integration) of the signal x[n]. You can therefore remove the loop using the MATLAB command cumsum and come up with
x = [1,2,2,1,4];
y = cumsum(x);
stem(y); % plot y

Related

Matlab Plotting by Conditional Statements

I am attempting to plot the wave equation for a single time step, t, in matlab based on an array of x that are passed into a function, u.
I am not very familiar with matlab and am not sure if this is the proper way to iterate through all x values and plot them. The process does not seem entirely similar to something like python and matplotlib.
EDIT: This code does not seem to be executing properly, how then can I iterate through the array and plot? ex: for element in x: do function
Thanks,
% defining the bounds of my x values
x=-10:.02:10;
% defining my time step, t
t = 1;
x1=[0 0];
y1=[-0.01 0.01];
x2=[-10 10];
y2=[0 0];
% defining some constants to make below equation simpler
xpt2= x + t;
xmt2= x - t;
% plotting based on the values of x - should iterate through the array?
if abs(x) > 1
u = 0.5 .* ((-(xpt2) .* exp(-abs(xpt2))./abs(xpt2)) + ((xmt2).*exp(-abs(xmt2))./abs(xmt2)));
plot(x,u,x1,y1,x2,y2);
xlabel('t=1');ylabel('u');
else
u = 0.5 .* abs(xpt2) + 0.5 .* abs(xmt2) + 0.5 .* (-(xpt2) .* exp(-abs(xpt2)./abs(xpt2)) + ((xmt2).*exp(-abs(xmt2))./abs(xmt2)));
plot(x,u,x1,y1,x2,y2);
xlabel('t=1');ylabel('u');
end
This code may not solve your issue but it may help you to find the error. I expect the error in the else part.
I use for loop to make if-clause work while #slayer way is more professional to work without a loop.
% defining the bounds of my x values
close all
clear
x=-10:.02:10;
% defining my time step, t
t = 1;
x1=[0 0];
y1=[-0.01 0.01];
x2=[-10 10];
y2=[0 0];
% defining some constants to make below equation simpler
xpt2= x + t;
xmt2= x - t;
% plotting based on the values of x - should iterate through the array?
for i=1:length(x)
if abs(x(i)) > 1
u(i) = 0.5 .* ((-(xpt2(i)) .* exp(-abs(xpt2(i)))./abs(xpt2(i))) + ((xmt2(i)).*exp(-abs(xmt2(i)))./abs(xmt2(i))));
else
u(i) = 0.5 .* abs(xpt2(i)) + 0.5 .* abs(xmt2(i)) + 0.5 .* (-(xpt2(i)) .* exp(-abs(xpt2(i))./abs(xpt2(i))) + ((xmt2(i)).*exp(-abs(xmt2(i)))./abs(xmt2(i))));
end
%display step by step
plot(x(1:i),u)
hold on
plot(x1,y1)
plot(x2,y2);
xlabel('t=1');ylabel('u');
pause(1/1000)
end
plot(x,u)
hold on
plot(x1,y1)
plot(x2,y2);
xlabel('t=1');ylabel('u');
You have a number of issues with your code.
1) Your conditional is on a vector so how can you check a conditional for every point in your vector? Well you can't this way.
2) You are taking the abs() of a vector but it looks like you want the negative parts to be accounted for? The abs([-1 0 1]) will return output [1 0 1], which makes your entire vector positive and remove the negative parts.
Now I see why you were asking for a for-loop to check the condition of every x variable in the vector. You can do that with:
for ii=1:numel(x) % This iterates through the vector
x(ii) % this accesses the current index of ii
end
But you still don't need a for loop. Instead use a conditional vector to keep track of the neg and pos points in x like:
idx_neg = x < 0; % boolean of all negative points in x
Then use the idx_neg on the vector you want the equation to be applied to. And the invert of the idx for the positive values like:
u = zeros(1, numel(x)); % initialize empty vector for storage
% for positive x values, use ~idx_neg to find the pos points
u(~idx_neg) = 0.5 .* ((-(xpt2(~idx_neg)) .* exp(-abs(xpt2(~idx_neg)))./abs(xpt2(~idx_neg))) + ((xmt2(~idx_neg)).*exp(-abs(xmt2(~idx_neg)))./abs(xmt2(~idx_neg))));
% now apply to neg points in x:
u(idx_neg) = 0.5 .* abs(xpt2(idx_neg(idx_neg))) + 0.5 .* abs(xmt2(idx_neg)) + 0.5 .* (-(xpt2(idx_neg)) .* exp(-abs(xpt2(idx_neg))./abs(xpt2(idx_neg))) + ((xmt2(idx_neg)).*exp(-abs(xmt2(idx_neg)))./abs(xmt2(idx_neg))));
I didn't check for syntax errors but this is basically what you are looking for.

Plotting cantilever and beam plots using Matlab

Problem
I have to plot a beam/cantilever using Matlab. Where my inputs are:
Length of the beam
Position of the loads (input is a vector)
Forces of the load (input is a vector)
Whether is it a cantilever or not. Because I have different equations for calculating the displacement.
My Solution
I have come to an idea on how I can actually plot the cantilever, but I can not formulate it into a code in MATLAB. I have spent hours trying to write something on Matlab but I have gotten nowhere. (I am a novice to Matlab)
My solution is as follow: I have the formula for the displacement from starting position.
I can define a vector using loop for x coordinates until the given beam length. Hence,
x=[0 ... L]
Then I want to define another vector where the difference is calculated (this is where I can't figure out Matlab)
y = [h, h - y(x1), h - y(x2), .... h - y(L)]
where h is the starting height, which I have thought to be defined as (y(x1) - y(L)) + 1, so that the graph then doesn't go into the negative axes. y(x) is the function which will calculate the displacement or fall of the beam.
Once that is done, then I can simply plot(x,y) and that would give me a graph of a shape of deflected beam for the given range from 0 to beam length. I have tested my theory on excel and it works as per the graph is concerned but I can not figure out implementation on Matlab.
My incomplete code
%Firstly we need the inputs
%Length of the beam
l = str2double(input('Insert the length of your beam: ', 's'));
%Now we need a vector for the positions of the load
a = [];
while 1
a(end+1) = input('Input the coordinate for the position of your load: ');
if length(a)>1; break; end
end
%Now we need a vector for the forces of the load
W = [];
while 1
W(end+1) = input('Input the forces of your load: ');
if length(W)>1; break; end
end
%
%
%
%Define the formula
y = ((W * (l - a) * x)/(6*E*I*l)) * (l^2 - x^2 - (l - a)^2);
%Where
E = 200*10^9;
I = 0.001;
%
%
%
%Now we try to plot
%Define a vector with the x values
vectx = [];
for i = 1:l
vectx = [vectx i];
end
%Now I want to calculate displacement for each x value from vectx
vecty = [];
for i=1:l
vecty=[10 - y(x(i)) i];
end
%Now I can plot all the information
plot(vectx, vecty)
hold on
%Now I plot the coordinate of the positions of the load
plot(load)
end
Really need some help/guidance. Would be truly grateful if someone can help me out or give me a hint :)
I have edited the question with further details
There are several things that do not work in your example.
For instance, parameters should be defined BEFORE you use them, so E and I should be defined before the deflection equation. And you should define x.
I do not understand why you put your inputs whithin a while loop, if you stop it at length(a)>1;. You can remove the loop.
You do not need a loop to calculate displacements, you can just use a substraction between vectors, like displacement = 10 - y. However, I do not understand what is H in your example; since your beam is initially at position 0, your displacement is just -y.
Finally, your equation to calculate the deformed shape is wrong; it only accounts for the first part of the beam.
Here, try if this code works:
%Length of the beam
l = input('Insert the length of your beam: ');
%Now we need a vector for the positions of the load
a = input('Input the coordinate for the position of your load: ');
%Now we need a vector for the forces of the load
W = input('Input the forces of your load: ');
%Define the formula
E = 200*10^9;
I = 0.001;
% x Position along the beam
x = linspace(0,l,100);
b = l - a;
% Deflection before the load position
pos = x <= a;
y(pos) = ((W * b .* x(pos))/(6*E*I*l)) .* (l^2 - x(pos).^2 - b^2);
% Cantilever option
% y(pos) = W*x(pos).^2/(6*E*I).*(3*a-x(pos));
% Deflection after the load position
pos = x > a;
y(pos) = ((W * b )/(6*E*I*l)) .* (l/b*(x(pos)-a).^3 + (l^2 - b^2)*x(pos) - x(pos).^3);
% Cantilever option
% y(pos) = W*a^2/(6*E*I).*(3*x(pos)-a);
displacement = 10 - y; % ???
% Plot beam
figure
plot(x , x .* 0 , 'k-')
hold on;
% Plot deflection
plot(x , y , '--')
% Plot load position
% Normalize arrow size as 1/10 of the beam length
quiver(a , 0 , 0 , sign(W) .* max(abs(y))/2)

How to implement a piecewise function and then plot it on certain intervals in MATLAB

I am actually attempting to write code for the cubic spline interpolation. Cubic spline boils down to a series of n-1 segments where n is the number of original coordinates given initially and the segments are each represented by some cubic function.
I have figured out how to get all the coefficients and values for each segment, stored in vectors a,b,c,d, but I don't know how to plot the function as a piecewise function on different intervals. Here is my code so far. The very last for loop is where I have attempted to plot each segment.
%initializations
x = [1 1.3 1.9 2.1 2.6 3.0 3.9 4.4 4.7 5.0 6 7 8 9.2 10.5 11.3 11.6 12 12.6 13 13.3].';
y = [1.3 1.5 1.85 2.1 2.6 2.7 2.4 2.15 2.05 2.1 2.25 2.3 2.25 1.95 1.4 0.9 0.7 0.6 0.5 0.4 0.25].';
%n is the amount of coordinates
n = length(x);
%solving for a-d for all n-1 segments
a = zeros(n,1);
b = zeros(n,1);
d = zeros(n,1);
%%%%%%%%%%%%%% SOLVE FOR a's %%%%%%%%%%%%%
%Condition (b) in Definition 3.10 on pg 146
%Sj(xj) = f(xj) aka yj
for j = 1: n
a(j) = y(j);
end
%initialize hj
h = zeros(n-1,1);
for j = 1: n-1
h(j) = x(j+1) - x(j);
end
A = zeros(n,n);
bv = zeros(n,1); %bv = b vector
%initialize corners to 1
A(1,1) = 1;
A(n,n) = 1;
%set main diagonal
for k = 2: n-1
A(k,k) = 2*(h(k-1) + h(k));
end
%set upper and then lower diagonals
for k = 2 : n-1
A(k,k+1) = h(k); %h2, h3, h4...hn-1
A(k,k-1) = h(k-1); %h1, h2, h3...hn
end
%fill up the b vector using equation in notes
%first and last spots are 0
for j = 2 : n-1
bv(j) = 3*(((a(j+1)-a(j)) / h(j)) - ((a(j) - a(j-1)) / h(j-1)));
end
%augmented matrix
A = [A bv];
%%%%%%%%%%%% BEGIN GAUSSIAN ELIMINATION %%%%%%%%%%%%%%%
offset = 1;
%will only need n-1 iterations since "first" pivot row is unchanged
for k = 1: n-1
%Searching from row p to row n for non-zero pivot
for p = k : n
if A(p,k) ~= 0;
break;
end
end
%row swapping using temp variable
if p ~= k
temp = A(p,:);
A(p,:) = A(k,:);
A(k,:) = temp;
end
%Eliminations to create Upper Triangular Form
for j = k+1:n
A(j,offset:n+1) = A(j,offset:n+1) - ((A(k, offset:n+1) * A(j,k)) / A(k,k));
end
offset = offset + 1;
end
c = zeros(n,1); %initializes vector of data of n rows, 1 column
%Backward Subsitution
%First, solve the nth equation
c(n) = A(n,n+1) / A(n,n);
%%%%%%%%%%%%%%%%% SOLVE FOR C's %%%%%%%%%%%%%%%%%%
%now solve the n-1 : 1 equations (the rest of them going backwards
for j = n-1:-1:1 %-1 means decrement
c(j) = A(j,n+1);
for k = j+1:n
c(j) = c(j) - A(j,k)*c(k);
end
c(j) = c(j)/A(j,j);
end
%%%%%%%%%%%%% SOLVE FOR B's and D's %%%%%%%%%%%%%%%%%%%%
for j = n-1 : -1 : 1
b(j) = ((a(j+1)-a(j)) / h(j)) - (h(j)*(2*c(j) + c(j+1)) / 3);
d(j) = (c(j+1) - c(j)) / 3*h(j);
end
%series of equation segments
for j = 1 : n-1
f = #(x) a(j) + b(j)*(x-x(j)) + c(j)*(x-x(j))^2 + d(j)*(x-x(j))^3;
end
plot(x,y,'o');
Let's assume that I have calculated vectors a,b,c,d correctly for each segment. How do I plot each cubic segment such that they all appear graphed on a single plot?
I appreciate the help.
That's pretty easy. You've already done half of the work by defining an anonymous function that is for the cubic spline in between each interval. However, you need to make sure that the operations in the function are element-wise. You currently have it operating on scalars, or assuming that we are using matrix operations. Don't do that. Use .* instead of * and .^ instead of ^. The reason why you need to do this is to make generating the points on the spline a lot easier, where my next point follows.
All you have to do next is define a bunch of x points within the interval defined by the neighbouring x key points and substitute them into your function, then plot the result.... so something like this:
figure;
hold on;
for j = 1 : n-1
f = #(x) a(j) + b(j).*(x-x(j)) + c(j).*(x-x(j)).^2 + d(j)*(x-x(j)).^3; %// Change function to element-wise operations - be careful
x0 = linspace(x(j), x(j+1)); %// Define set of points
y0 = f(x0); %// Find output points
plot(x0, y0, 'r'); %// Plot the line in between the key points
end
plot(x, y, 'bo');
We spawn a new figure, then use hold on so that when we call plot multiple times, we append the results to the same figure. Next, for each set of cubic spline coefficients we have, define a spline function, then generate a bunch of x values with linspace that are between the current x key point and the one beside it. By default, linspace generates 100 points between a start point (i.e. x(j)) and end point (i.e. x(j+1)). You can control how many points you want to generate by specifying a third parameter (so something like linspace(x(j), x(j+1), 25); to generate 25 points). We use these x values and substitute them into our spline equation to get our y values. We then plot this result on the figure using a red line. Once we're done, we plot the key points as blue open circles on top of the curve.
As a bonus, I ran your code with the above plotting mechanism, and this is what I get:

Using MATLAB to write a function that implements Newton's method in two dimensions

I am trying to write a function that implements Newton's method in two dimensions and whilst I have done this, I have to now adjust my script so that the input parameters of my function must be f(x) in a column vector, the Jacobian matrix of f(x), the initial guess x0 and the tolerance where the function f(x) and its Jacobian matrix are in separate .m files.
As an example of a script I wrote that implements Newton's method, I have:
n=0; %initialize iteration counter
eps=1; %initialize error
x=[1;1]; %set starting value
%Computation loop
while eps>1e-10&n<100
g=[x(1)^2+x(2)^3-1;x(1)^4-x(2)^4+x(1)*x(2)]; %g(x)
eps=abs(g(1))+abs(g(2)); %error
Jg=[2*x(1),3*x(2)^2;4*x(1)^3+x(2),-4*x(2)^3+x(1)]; %Jacobian
y=x-Jg\g; %iterate
x=y; %update x
n=n+1; %counter+1
end
n,x,eps %display end values
So with this script, I had implemented the function and the Jacobian matrix into the actual script and I am struggling to work out how I can actually create a script with the input parameters required.
Thanks!
If you don't mind, I'd like to restructure your code so that it is more dynamic and more user friendly to read.
Let's start with some preliminaries. If you want to make your script truly dynamic, then I would recommend that you use the Symbolic Math Toolbox. This way, you can use MATLAB to tackle derivatives of functions for you. You first need to use the syms command, followed by any variable you want. This tells MATLAB that you are now going to treat this variable as "symbolic" (i.e. not a constant). Let's start with some basics:
syms x;
y = 2*x^2 + 6*x + 3;
dy = diff(y); % Derivative with respect to x. Should give 4*x + 6;
out = subs(y, 3); % The subs command will substitute all x's in y with the value 3
% This should give 2*(3^2) + 6*3 + 3 = 39
Because this is 2D, we're going to need 2D functions... so let's define x and y as variables. The way you call the subs command will be slightly different:
syms x, y; % Two variables now
z = 2*x*y^2 + 6*y + x;
dzx = diff(z, 'x'); % Differentiate with respect to x - Should give 2*y^2 + 1
dzy = diff(z, 'y'); % Differentiate with respect to y - Should give 4*x*y + 6
out = subs(z, {x, y}, [2, 3]); % For z, with variables x,y, substitute x = 2, y = 3
% Should give 56
One more thing... we can place equations into vectors or matrices and use subs to simultaneously substitute all values of x and y into each equation.
syms x, y;
z1 = 3*x + 6*y + 3;
z2 = 3*y + 4*y + 4;
f = [z1; z2];
out = subs(f, {x,y}, [2, 3]); % Produces a 2 x 1 vector with [27; 25]
We can do the same thing for matrices, but for brevity I won't show you how to do that. I will defer to the code and you can see it then.
Now that we have that established, let's tackle your code one piece at a time to truly make this dynamic. Your function requires the initial guess x0, the function f(x) as a column vector, the Jacobian matrix as a 2 x 2 matrix and the tolerance tol.
Before you run your script, you will need to generate your parameters:
syms x y; % Make x,y symbolic
f1 = x^2 + y^3 - 1; % Make your two equations (from your example)
f2 = x^4 - y^4 + x*y;
f = [f1; f2]; % f(x) vector
% Jacobian matrix
J = [diff(f1, 'x') diff(f1, 'y'); diff(f2, 'x') diff(f2, 'y')];
% Initial vector
x0 = [1; 1];
% Tolerance:
tol = 1e-10;
Now, make your script into a function:
% To run in MATLAB, do:
% [n, xout, tol] = Jacobian2D(f, J, x0, tol);
% disp('n = '); disp(n); disp('x = '); disp(xout); disp('tol = '); disp(tol);
function [n, xout, tol] = Jacobian2D(f, J, x0, tol)
% Just to be sure...
syms x, y;
% Initialize error
ep = 1; % Note: eps is a reserved keyword in MATLAB
% Initialize counter
n = 0;
% For the beginning of the loop
% Must transpose into a row vector as this is required by subs
xout = x0';
% Computation loop
while ep > tol && n < 100
g = subs(f, {x,y}, xout); %g(x)
ep = abs(g(1)) + abs(g(2)); %error
Jg = subs(J, {x,y}, xout); %Jacobian
yout = xout - Jg\g; %iterate
xout = yout; %update x
n = n + 1; %counter+1
end
% Transpose and convert back to number representation
xout = double(xout');
I should probably tell you that when you're doing computation using the Symbolic Math Toolbox, the data type of the numbers as you're calculating them are a sym object. You probably want to convert these back into real numbers and so you can use double to cast them back. However, if you leave them in the sym format, it displays your numbers as neat fractions if that's what you're looking for. Cast to double if you want the decimal point representation.
Now when you run this function, it should give you what you're looking for. I have not tested this code, but I'm pretty sure this will work.
Happy to answer any more questions you may have. Hope this helps.
Cheers!

how to output all the iteration results from a FOR loop into matrix and plot the graph

I have two for loops in a nested format. My second loop calculates the final equation. The display of the result is outside the second loop in order to display when the second loop is complete.
Below is the logic I used in MATLAB. I need to plot graph of eqn2 vs x.
L=100
for x=1:10
eqn1
for y=1:L
eqn2
end
value = num2strn eqn2
disp value
end
Currently the problem I am facing is that value or output of eqn2 is always replaced after each cycle until x reaches 10. Hence, the workspace table of eqn2 and value only shows the last value. My intention is to document all the output values of value in every cycle of x from 1:10.
How can I do this?
You pseudo-coded a little too strongly for my taste - I have tried to reconstruct what you were trying to do. If I understood correctly, this should do address your question (store intermediate results from the calculation in array Z):
L=100
z = zeros(L,10);
for x=1:10
% perform some calculations
eqn1
for y=1:L
% perform some more calculations; it is not clear whether the result of
% this loop over y=1:L yields one value, or L. I am going to assume L values
z(y, x) = eqn2(x, y)
end
value =num2strn eqn2
disp value
end
% now you have the value of each evaluation of the innermost loop available. You can plot it as follows:
figure;
plot( x, z); % multiple plots with a common x parameter; may need to use Z' (transpose)...
title 'this is my plot';
xlabel 'this is the x axis';
ylabel 'this is the y axis';
As for the other questions you asked in your comments, you could probably findd inspiration in the following:
L = 100;
nx = 20; ny = 99; % I am choosing how many x and y values to test
Z = zeros(ny, nx); % allocate space for the results
x = linspace(0, 10, nx); % x and y don't need to be integers
y = linspace(1, L, ny);
myFlag = 0; % flag can be used for breaking out of both loops
for xi = 1:nx % xi and yi are integers
for yi = 1:ny
% evaluate "some function" of x(xi) and y(yi)
% note that these are not constrained to be integers
Z(yi, xi) = (x(xi)-4).^2 + 3*(y(yi)-5).^2+2;
% the break condition you were asking for
if Z(yi, xi) < 5
fprintf(1, 'Z less than 5 with x=%.1f and y=%.1f\n', x(xi), y(yi));
myFlag = 1; % set flag so we break out of both loops
break
end
end
if myFlag==1, break; end % break out of the outer loop as well
end
This may not be what you had in mind - I cannot understand "run the loop untill all the values of z(y,x) <5 and then it should output x". If you run the outer loop to completion (that's the only way you know "all the values of z(y,x)" then your value of x will be the last value it was... This is why I was suggesting running through all values of x and y, collecting the whole matrix Z, and then examining Z for the things you want.
For example, if you wonder if there is a value for X for which all Z < 5, you could do this (if you didn't break out of the for loops):
highestZ = max(Z, [], 1); % "take the highest value of Z in the 1 dimension
fprintf(1, 'Z is always < 5 for x = %d\n', x(highestZ<5));
etc.
If you can't figure it out from here, I give up...