Error using stem X must be same length as Y - matlab

im trying to find the even and odd part of the x array but it returns me error using stem, X must be same length as Y this is my code in matlab
close all;
clear all;
clc;
n1 = -5:1:5;
AM = 19390;
x = [1,9,3,9,0,1,1,9,3,9,0];
fun(x,n1);
function [sima,xr] = fun(t,x)
x_reverse = fliplr(x);% time reversal
sima = 0.5*(x + x_reverse); %even component
xr = 0.5*(x - x_reverse); %odd component
subplot(3,1,1);
stem(t,x);
title('Your signal x')
subplot(3,1,2);
stem(t,sima);
title('Even part');
subplot(3,1,3);
stem(t,xr);
title('Odd part');
end

the inputs of fun are reversed.
where you write
fun(x,n1)
you should have
fun(n1,x)
this or reverse the order of each reference and value vectors for each stem inside fun.

Related

Unable to perform assignment because the size of the left side is 1-by-2 and the size of the right side is 2-by-2

the code tries to implement the Euler's method and improve Euler's method to second order differential equations but there is a dimensionality error with the ys values array which store the values of y and dy
f=#(x,y) [y(2); (2/x)*y(2)-(2/x^2)*y(1)]; % function through a function handle
x0 = 1; y0 = [4,9]; xf=2; % IC
% Improve and Euler's Method
[xs,ys] = ode45(f,[x0,xf],y0);
[xsi1,ysi1] = Ieuler(f,[x0,xf],y0,0.1);
[xse1,yse1] = euler(f,[x0,xf],y0,0.1);
[xsi2,ysi2] = Ieuler(f,[x0,xf],y0,0.5);
[xse2,yse2] = euler(f,[x0,xf],y0,0.5);
% plotting all solutions
plot(xsi1,ysi1(:,1),'-b','LineWidth',1.5); hold on;
plot(xse1,yse1(:,1),'-r','LineWidth',1.5); hold on;
plot(xsi2,ysi2(:,1),'-g','LineWidth',1.5); hold on;
plot(xse2,yse2(:,1),'-k','LineWidth',1.5); hold on;
plot(xs,ys(:,1),'-b','LineWidth',1.5); hold on;
axis([0 xf -0.1 4]); xlabel('x');ylabel('y')
In the second part of the code are the constructed function to implement Euler's method
%Function calls
% function: Euler's Method implementation
function [xs,ys] = euler(f,xv,y0,h)
x0 = xv(1); X = xv(2);
N = (X-x0)/h;
xs = zeros(N+1,1); ys = zeros(N+1,length(y0));
x = x0; y = y0;
xs(1) = x; ys(1,:) = y';
for i = 1:N
s1 = f(x,y); %evaluate direction field at current point
y= y+s1*h; %find new y
x = x+h;
xs(i+1) = x; ys(i+1,:) = y'; %store y(1), y(2) in a row array
end
end
% function: Improved Euler's Method implementation
function [xs,ys] = Ieuler(f,xv,y0,h)
x0 = xv(1); X = xv(2);
N = (X-x0)/h;
xs = zeros(N+1,1); ys = zeros(N+1,length(y0));
x = x0; y = y0;
xs(1) = x; ys(1,:) = y';
for i = 1:N
s1 = f(x,y); %evaluate direction field at current point
yE= y+s1*h; %find Euler value yE
s2 = f(x+h,yE); %evalute direction field at Euler point
y = y + h*((s1+s2)/2); *%find new y*
x = x+h;
xs(i+1) = x; ys(i+1,:) = y'; *%store y(1), y(2) in a row array*
end
end
Unable to perform assignment because the size of the left side is 1-by-2 and the
size of the right side is 2-by-2.
Error in Untitled>Ieuler (line 63)
xs(i) = x; ys(i,:) = y';
Error in Untitled (line 20)
[xsi1,ysi1] = Ieuler(f,[x0,xf],y0,0.1);
stop writing several logic lines (terminated with a ;) in one text
line. It is not even clear, which command causes the error, since
there are two in this line! (BTW, it is this ys(i+1,:) = y';)
strip your code. You should provide a minimal reproducible example
(its not an art contest... and as the error occurs in Ieuler the rest is not necessary).
your error is: that your function handle ´f´ returns a vector, but y is an array => you'll get a matrix, which you want to assign to an array ys(i+1,:) = y' (for whatever reason you are transposing this). solution: let f return an array: f=#(x,y) [y(2), (2/x)*y(2)-(2/x^2)*y(1)]; (note the comma) or transpose its return value s1 = f(x,y).'; (its good practice to use the .' for non-complex transpositions -- for clarity.
Advice: have a look how to debug in MATLAB. You probably could have tracked this down by placing a breakpoint just before the line where the error occurs (or even activate Pause on Errors) and checking the dimensions.

Integrate over a meshgrid space

Currently I'm working on a project trying to recreate Young's original experiment. To make a long story short, I have a rather complicated surface defined using matlab's meshgrid and I want to evaluate my defined function (fun in the code) over this surface.
My code is currently looking like this:
clc;
clear all ;
M = 20 ;
N = 100 ;
R1 = 1 ; % yttre radien
nR = linspace(0,R1,M) ;
nT = linspace(0,2*pi,N) ;
nx = linspace(-0.1,0.9,N);
ny = linspace(-1,1,M);
%nT = pi/180*(0:NT:theta) ;
[B, Z] = meshgrid(nx,ny);
[R, T] = meshgrid(nR,nT) ;
lambda = 1;
fun= #(s) e^((i*2*pi/lambda)*(1/2 * (cos(lambda/(4*pi*s))/2)));
% Convert grid to cartesian coordintes
X = R.*cos(T);
Y = R.*sin(T);
[m,n]=size(X);
% Plot grid
figure
set(gcf,'color','w') ;
axis equal
axis off
box on
hold on
for i=1:m
plot(X(i,:),Y(i,:),'k','linewidth',1.5);
end
for j=1:n
plot(X(:,j),Y(:,j),'k','linewidth',1.5);
plot(B(:,j),Z(:,j),'b','linewidth',1.5);
end
If you try to run my code, I want to evalute the function fun over all the space in the meshgrid except for the blue part, can this be done or should I restart and approach the problem in a different way? Thanks in advance

plotting eigenvector in Matlab

I'm trying to plot a the eigenvectors of a 2D Dataset, for that I'm trying to use the quiver function in Matlab, here's what I've done so far :
% generating 2D data
clear ;
s = [2 2]
set = randn(200,1);
x = normrnd(s(1).*set,1)+3
y = normrnd(s(1).*set,1)+2
x_0 = mean(x)
y_0 = mean (y)
c = linspace(1,100,length(x)); % color
scatter(x,y,100,c,'filled')
xlabel('1st Feature : x')
ylabel('2nd Feature : y')
title('2D dataset')
grid on
% gettign the covariance matrix
covariance = cov([x,y])
% getting the eigenvalues and the eigenwert
[eigen_vector, eigen_values] = eig(covariance)
eigen_value_1 = eigen_values(1,1)
eigen_vector_1 =eigen_vector(:,1)
eigen_value_2 = eigen_values(2,2)
eigen_vector_2 =eigen_vector(:,2)
% ploting the eigenvectors !
hold on
quiver(x_0, y_0,eigen_vector_2*(eigen_value_2),eigen_vector_1*(eigen_value_1))
My problem is the last line, I get the following error :
Error using quiver (line 44)
The size of Y must match the size of U or the number of rows of U.
It seems that I'm missing a size here but I can't figure out where!
thanks in advance for any hint
As the error says, X and Y parameters must have, respectively, the same size of U and V parameters. If you change the last part of your code:
% ploting the eigenvectors !
hold on
quiver(x_0, y_0,eigen_vector_2*(eigen_value_2),eigen_vector_1*(eigen_value_1))
as follows:
x_0 = repmat(x_0,size(eigen_vector_2,1),1);
y_0 = repmat(x_0,size(eigen_vector_1,1),1);
% ploting the eigenvectors !
hold on;
quiver(x_0, y_0,eigen_vector_2*(eigen_value_2),eigen_vector_1*(eigen_value_1));
hold off;
your script should properly work.

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)

Drawing a line in matlab plot

I am beginner in matlab programming, so i wrote this little programm to see it in action, and now I have a little problem because I am not sure why it is not working.
x = zeros(50);
squared = zeros(50);
cubed = zeros(50);
for num = 1:50
x(num) = num;
squared(num) = num^2;
cubed(num) = num^3;
end
% calculate the mean
mean_cubed = mean(cubed);
% clear screen and hold the plot
clf;
hold on
plot(x, squared);
plot(x, cubed);
plot([0, 50], [mean_cubed, mean_cubed]);
hold off
The main program is when i start the program i get a error:
Error using plot
Vectors must be the same lengths.
Error in basic_mathlab_plotting_2 (line 20)
plot([0, limit], [mean_cubed, mean_cubed]);
I think the size of vector are the same, so i dont know what is wrong.
Thanks!!!
In the first lines, you probably meant
x = zeros(1,50);
squared = zeros(1,50);
cubed = zeros(1,50);
Note that zeros(50) is equivalent to zeros(50,50) and so it returns a 50x50 matrix.
In addition, those lines and the for loop could be replaced by
x = 1:50;
squared = x.^2;
cubed = x.^3;
This applies the important concept of vectorization, by using the element-wise power operation.