Matlab error , matrix dimensions dont agree - matlab

im trying to plot 2 figures, using fplot and plot functions, but for my plot (fig2) , i get an error and don't understand why;
Error using /
Matrix dimensions must agree.
Error in bhpfilter (line 9)
H = 3*g / ( (fo/f).^2 + 3*(fo/f)+3);
Error in #(f)bhpfilter(f,fo,g)
function [H] = bhpfilter(f, fo, g)
%freq finds the filter frequency response in V/V
%fo is the cut off frequency, f is the input frequency and g is the filter
%gain
if fo <= 0 || g <=0 %error checking
error('Inputs invalid');
else
H = 3*g / ( (fo/f).^2 + 3*(fo/f)+3);
end
fo=1200.;
g=2.;
H =#(f) bhpfilter(f,fo,g);
H_1 = #(f) bhpfilter (f,fo,g)-0.8;
figure (1);
fplot(H,[0 2000]);
title('Plot of H vs f using fplot');
xlabel('Frequency (Hz)');
ylabel('Filter frequency response (V/V)');
fprintf('The value of f that gives a response of 0.8 is %f Hz\n',fzero (H_1, [0 2000])); %placed this line of code here so that it can be visible in command window , showing it works
figure (2);
plot([0:2000],H([0:2000])); % code will find individual values of H(1), H(2) etc.. but will not find H([0:200])
title('Plot of H vs f using plot');
xlabel('Frequency (Hz)');
ylabel('Filter frequency response (V/V)');

In the line H = 3*g / ( (fo/f).^2 + 3*(fo/f)+3); g and fo are scalars while f is a vector. For division MATLAB doesn't recognize the divide operator as element by element division when it is scalar/vector (it does for the other way around). You have to put:
H = 3*g ./ ( (fo./f).^2 + 3*(fo./f)+3);
Hope that helps.

Related

Error using stem X must be same length as Y

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.

Vector size mismatch in MATLAB

I have been trying to write down a code for an LTI system where the response is calculated from an input x(t) and impulse h(t) response.
For the part of the code below:
y = conv(x,h).*steps;
ty = 0:steps:7;
plot(ty,y);
I'm getting the following error message:
Error using plot
Vectors must be the same length.
I'm using ty = 0:steps:7; as h(t) is defined as exp(-t/2).*((t>=2)-(t>=7)) (since it extends upto t=7).
What does actually decide ty?
Convolution Using Anonymous Functions
One way to do this process is to use anonymous functions/functions handles which are indicated by the #() that holds the input parameters in this case time, t. To create truncated signals conditional statements on t can be implemented. To have a signal ranging from t=2 to t=7 seconds truncation can be done by element-wise multiplying by ((t>=2) & (t<=7)). The t vector used to plot the final result must have a time range that is the sum of the lengths of time of the signals used in the convolution process. I believe ty is the time vector to plot the output against. In this case you must ensure ty has the same length as the output y.
Length of Results = Length of System Response + Length of Input Signal
In the case below:
x(t) → length = 1s
h(t) → length = 5s (2s to 7s)
y(t) → length = 1s + 5s = 6s (2s to 8s)
Step_Size = 0.1;
Start_Time = 0; End_Time = 7;
t = Start_Time: Step_Size: End_Time;
%Input into system x(t)%
x = #(t) 1.0.*(t >= 0 & t <= 1);
subplot(3,1,2); fplot(x);
title('x(t): Input into system');
xlabel('Time (s)'); ylabel('Amplitude');
xlim([0 10]);
ylim([0 1.1]);
%System impulse response h(t)%
h = #(t) exp(-t/2).*((t>=2) & (t<=7));
subplot(3,1,1); fplot(h);
title('h(t): System impulse response');
xlabel('Time (s)'); ylabel('Amplitude');
xlim([0 10]);
y = conv(x(t),h(t)).*Step_Size;
t = linspace(0,2*max(t),length(y));
subplot(3,1,3); plot(t,y);
title('y(t): Output/System Response');
xlabel('Time (s)'); ylabel('Amplitude');

How do I plot the solutions and errors obtained through Jacobi Iteration?

I am trying to create a figure showing the solution I obtained through Jacobi iteration along with the true solution, as well as the error of the Jacobi solution.
The figure I'm trying to create should consist of two plots.
I used the subplot command, to split the figure into
an upper and lower axes and I wrote the for loop that calculates the Jacobi iterations and the error. The loop is going to iterate 400 times using x0 as the initial guess. Before this, I calculated the true solution to the system Ax = b.
N = 30;
iter = 400;
A = toeplitz([-2 1 zeros(1, N-2)], [-2 1 zeros(1, N-2)]);
bk = ones(N,1);
for jj = 1:N
bk(jj) = cos(5*jj) + (1/2)*sin(7*jj);
end
x = A\bk;
D = diag(diag(A));
T = A - D;
x0 = zeros(N,1);
error = zeros(iter,1);
M = -D\T;
g = D\bk;
for nn = 1:iter
x0 = M*x0 + g;
error(nn) = norm(x - x0,2);
end
subplot(2,1,1)
plot(x0(1:N,1),'ro');
ylabel('Solution','FontSize',22);
title('Solution by Jacobi Iteration','FontSize',22);
xlim([0 pi]);
ylim([-5 5]);
xticks(0:0.5:3);
yticks(-5:5:5);
subplot(2,1,2)
plot(error(1:N),'ro')
ylabel('Error','FontSize',22);
xlabel('t','FontSize',22);
xlim([0 pi]);
ylim([0 0.1]);
xticks(0:0.5:3);
yticks(0:0.05:0.1);
The upper window should show the true solution in red circles connected by solid lines. The lower window show show the error as red
circles connected by dotted lines. When I ran my code, only 3 red circles appeared in the upper window and nothing was plotted in the lower window. I'm still bad at plotting iterations of a loop. Can someone help me with plotting the solutions and errors I calculated?
The xlim and ylim statements are not representative of the data.
x0 and x have N elements (30 here), and the elements of x and x0 span -2 to 2 in this setup.
error has iter elements (400 here), and the elements of error go from 4 to about 0.01.
For these plots, the element index maps to the horizontal x-axis, and their values to the y-axis. I think this plot setup should give you the result you desire (I probably changed more than actually needed):
subplot(2,1,1);
plot(1:N, x0(1:N,1), 'ro', 1:N, x,'k+');
title('Solution by Jacobi Iteration','FontSize',22);
ylabel('Solution','FontSize',22);
xlim([1, N]);
ylim([-3, 3]);
xticks(1:N);
yticks(-3:0.5:3);
subplot(2,1,2)
semilogy(1:iter, error(1:iter),'ro')
ylabel('Error','FontSize',22);
xlabel('t','FontSize',22);
xlim([1 iter]);
ylim([0 4]);
xticks(0:25:400);

ezplot in MATLAB, how to plot using a function handle?

I've tried this:
linefunca = #(xa,ya) aa*xa + ba*ya + ca;
figure(1)
imshow(Pica);
hold on;
ezplot(linefunca,[1,1072,1,712]);
But I'm returned with this error:
In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in ezplotfeval/applyfun (line 80)
z(i) = feval(f,x(i),y(i));
Error in ezplotfeval (line 65)
z = applyfun(x,y);
Error in ezplot>ezimplicit (line 257)
u = ezplotfeval(f, X, Y);
Error in ezplot (line 153)
hp = ezimplicit(cax, f{1}, vars, labels, args{:});
Error in ps3 (line 313)
ezplot(linefunca,[1,1072,1,712]);
aa,ba,ca are all known values (column vectors). The x and y limits are the size of the image that I'm working with. I'm trying to plot a set of epipolar lines. Any suggestions?
EDIT:
lt = length(aa);
linefunca = #(x,y,t) aa.*x(t) + ba.*y(t) + ca(t);
figure(1)
imshow(Pica);
hold on;
for t=1:lt
ezplot(#(x,y,t) linefunca(x,y,t),[1,lt]);
end
As far as I know, ezplot can not plot a series of lines like plot. A way to work around this would be to add a parameter k to the anonymous function, which is used to select the current line. You can then go through all lines in a for loop and plot them one-by-one.
Further: as it is stated on the ezplot help page, you have to use the array functions .*, ./ and .^ , so ezplot can use vectors to evaluate the function.
N = 5;
aa = rand(N,1); ba = rand(N,1); ca = rand(N,1);
linefunca = #(xa,ya,k) aa(k).*xa + ba(k).*ya + ca(k);
hold on
for k=1:N
ezplot(#(x,y)linefunca(x,y,k),[-5,5,-5,5]);
end
hold off

How to plot a function using a code that I wrote with a starting point?

I wrote the code for the secant algorithm , and now I have the function :
f(x) = 2x^3 - 4x^2 + 3x , with two initial points : x0 = -1 , x1 = 2 .
My question is how can I plot the function that I wrote ,i.e. secant , with the function above , f , and the results below , in one graph ?
Is it even possible to do that ?
The results that I got after I used the secant algorithm , are :
v =
-4.0000
2.2069
2.3699
2.6617
2.5683
2.5804
Those are 6 iterations that I used on my secant algorithm , for the given x0 & x1 above .
I'd appreciate if you can explain .
EDIT :
This is the code that I used in order to get the results :
[z,n,v]=secant([-1,2],10^(-5),10^(-5),10)
for the prototype :
function [x,n,v]=secant(X,d,e,N)
% x0 is the first point
% x1 is the end point
% d is the tolerance
% e is the requested precision
% N is the number of iterations
Thanks .
I quickly threw this together, it illustrates the powerful anonymous function
and it shows you how to plot the results of the secant function (the same way as on wikipedia: http://en.wikipedia.org/wiki/File:Secant_method.svg)
What I don't understand however is why your secant function has both a tolerance and a requested precision as an input; I would think the tolerance is the result of the secant algorithm..
function [ ] = tmp1( )
f=#(x) x.^2;
[xend,n,v]=secant(f,-4,3,1e-4,50);
fprintf('after %d iterations reached final x_end = %g, f(x_end) = %g\n',n,xend,f(xend))
figure;hold on;
xtmp = linspace(min(v),max(v),250);
plot(xtmp,f(xtmp),'r'); % plot the function itself
line([v(1:end-2) v(3:end)]',[f(v(1:end-2)) zeros(n+1,1)]','Color','b','Marker','.','MarkerEdgeColor','b'); % plot the secant lines
plot(v,f(v),'.','MarkerEdgeColor','r')% plot the intermediate points of the secant algorithm
line([v(3:end) v(3:end)]',[zeros(n+1,1) f(v(3:end))]','Color','k','LineStyle','--'); % vertical lines
ylim([-4 max(f(xtmp))]); % set y axis limits for nice plotting view algorithm
end
function [xnew,n,v]=secant(f, x0,x1,e,N)
% x0 is the first point
% x_end is the end point
% e is the requested precision
% N is the number of iterations
v=zeros(N+2,1);
v(1)=x0;
v(2)=x1;
for n=0:N-1
xnew = x1 - f(x1) * (x1-x0)/(f(x1)-f(x0));
v(3+n) = xnew;
if abs(f(xnew)) <e
break;
else
x0=x1;
x1=xnew;
end
end
v(n+4:end)=[];
end
You can plot the function, and the results as scatter points.
First, define the function in a vectorical way:
f(x) = #(x) ( 2*x.^3 - 4*x.^2 + 3*x );
Then draw the function over some range:
x = -10:10;
y = f(x);
figure(); plot(x,y);
Now, show the resuls:
hold on;
scatter(v,f(v));