Local Minimum in MATLAB? - matlab

I'm simply trying to find the exact minimum of a simple function in MATLAB. I've been experimenting with the use of built-in functions such as "fminbnd" and inline function definition, but I don't think I quite know what I'm doing.
My code is below. I want to find the x and y of Error's minimum.
clear all
A = 5;
tau = linspace(1,4,500); %Array of many tau values between 1 and 4
E1 = qfunc(((-tau) + 5) /(sqrt(2.5)));
E0 = qfunc((tau)/(sqrt(2.5)));
Error = 0.5*E0 + 0.5*E1;
figure
subplot (311), plot(tau, E0);
xlabel('Threshold (Tau)'), ylabel('E0')
title('Error vs. Threshold (E0, 1 <= T <= 4)')
subplot (312), plot(tau, E1);
xlabel('Threshold (Tau)'), ylabel('E1')
title('Error vs. Threshold (E1, 1 <= T <= 4)')
subplot (313), plot(tau, Error);
xlabel('Threshold (Tau)'), ylabel('Pr[Error]');
title('Error vs. Threshold (Pr[Error], 1 <= T <= 4)')
I mean, I can use the cursor when the function is graphed to get close (though not right at the point where it occurs (Threshold = 2.5), but there must be a method just to print the number to the window. So far I have tried:
fminbnd('Error', 'E0', 'E1')
And many other variants. Also tried using anonymous and inline function definitions with no luck.
Can anyone point me in the right direction? Feel foolish for being stuck with this simple problem... Any help greatly appreciated!

See fminbnd
You should try something like this:
Error =#(tau) 0.5*qfunc(((-tau) + 5) /(sqrt(2.5))) + 0.5*qfunc((tau)/(sqrt(2.5)));
x = fminbnd(Error,0,10)
The first argument of fminbnd(f,x1,x2) is the function and the other arguments are the bounds. I did f=Error, x1=0 and x2=10.
Output:
x=2.5000
Another way is to save your error function in .m file. See the webpage above.

I don't understand why you're using E0 and E1 as the limits of the range where the minimum should be found. Or am I misunderstanding something in your code?
Maybe if you have your function as a discrete collection of samples (as seems implied from your way of constructing it, error is going to be a matrix, I think), you could use the "min" command: http://www.mathworks.es/es/help/matlab/ref/min.html
Hope this helped!

Related

interval spacing on matlab

Hi I'm new to matlab and programming in general and I was wondering if anyone could tell me whats wrong with my code.
These were my instructions and values
Complete the implementation of the dampedOsc function, which evaluates and plots a graph showing the function y=e-0.8xcos 3x at a
set of points spaced at intervals of 0.1 and ranging from 0 to 3π.
The curve should be displayed using a magenta dotted line with
'pentagram' markers.
and my code:
function y = dampedOsc(x)
fplot(#(x) (exp(-0.8*x)*cos(3*x)),[0 3*pi()],'mp:')
end
All tests passed except this one:
Test 1 (Test that function has been plotted):
Actual value does not have correct size:
expectedSize =
1 95
actualSize =
1 98
Test failed.
I honestly have no idea whats gone wrong, I thought it was because of the lack
of point spaced intervals but I have no idea how to input it.
This is an interesting question, so I'll give it a stab. I would probably do something like this.
function z = dampedOsc(x)
if isvector(x) == 0
return
else
z = zeros(1,length(x));
for n = 1 : length(x)
y = exp(-0.8 .* x(n)) .* cos(3 .* x(n));
z(1,n) = y;
end
end
z
end
Then, calling that dampedOsc function from another script, should give the figure.
plot([0 : 0.1 : (3*pi)],dampedOsc(x),'mp:')
I don't have MATLAB in front of me right now, but I think this should work. If it doesn't, I can fix it. Good luck with your project!

matlab help in finding dimensions

Can anybody help me with this assignment please?
I am new to matlab, and passing this year depends on this assignment, i don't have much time to explore matlab and i already wasted alot of time trying to do this assignment in my way.
I have already wrote the equations on the paper, but transfering the equations into matlab codes is really hard for me.
All i have for now is:
syms h
l = (0.75-h.^2)/(3*sqrt((5*h.^2)/4)); %h is h_max
V_default = (h.^2/2)*l;
dv = diff(V_default); %it's max. when the derivative is max.
h1 = solve( dv ==0);
h_max = (h1>0);
l_max = (0.75-h_max.^2)/(3*sqrt((h_max/2).^2+(h_max.^2)));
V_max = ((h_max.^2)./(2.*l_max));
but it keep give me error "Error using ./
Matrix dimensions must agree.
Error in triangle (line 9)
V_max = ((h_max.^2)./(2.*l_max)); "
Not really helping with the assignment here, but with the Matlab syntax. In the following line:
l_max = (0.75-h_max.^2)/(3*sqrt((h_max/2).^2+(h_max.^2)));
you're using / that is a matrix divide. You might want to use ./ which will divide the terms element by element. If I do this
l_max = (0.75-h_max.^2) ./ (3*sqrt((h_max/2).^2+(h_max.^2)));
then your code doesn't return any error. But I have no idea if it's the correct solution of your assignment, I'll leave that to you!
In line 5, the result h1 is a vector of two values but the variable itself remains symbolic, from the Symbolic Math Toolbox. MATLAB treats such variables slightly different. For that reason, the line h_max = (h1>0) doesn't really do what you expect. As I think from this point, you are interested in one value h_max, I would convert h1 to a regular MATLAB variable and change your code to the following:
h1 = double(solve( dv ==0)); % converts symbolic to regular vectors
h_max = h1(h1>0); % filters out all negative and zero values
l_max = (0.75-h_max.^2)/(3*sqrt((h_max/2).^2+(h_max.^2)));
V_max = ((h_max.^2)./(2.*l_max));
EDIT.
If you still have error, it means solve( ...) returns more than 1 positive values. In this case, as suggested, use dotted operations, such as ./ but the results in l_max and V_max will not be a single value but vectors of the same size as h_max. Which means you don't have one max Volume.

Writing a function in matlab syntax

I wrote a function named "Maximizing Gross margin" that is used in agriculture. The formula is like this:
max sigma(i=1 to n) sigma(j=1 to nc) (Pij * Yij - SDij ... (and so on) ) ...
full formula in this link:
http://i.stack.imgur.com/fMSiU.jpg
I think it doesn't have the real matlab's syntax and it is not really calculates the maximum. And there are two other formulas that I want to mix with this and link them to the evolutionary algorithm (NSGA-II) and I really don't know how, although I confused myself searching for it.
This is my function in matlab:
function gx = costfunction( p,y,sd,fer,lb,oc,a,wp,Q,ma)
SigmaQNC = zeros(5,3);
SigmaNC = zeros(5,3);
for i=1:5
for j=1:3
SigmaQNC(i,j) = SigmaQNC(i,j) + Q(i,1);
SigmaNC(i,j) = (p(i,j).*y(i,j))-(sd(i,j)-fer(i,j)-lb(i,j)-oc(i,j)-ma(i,j)).*a(i,j)-wp(i,j).*SigmaQNC(i,j);
sort(SigmaNC);
end
end
gx=SigmaNC;
end
The question is, how to really write it in matlab syntax and how to link these three formulas to NSGA-II with the limitations (like min Aij <= percentage Aij <= max Aij )
Any kind of help would be appreciated.
Yes, your formula is not in MATLAB syntax. If I understood correctly, you want to maximize this objective function which is done by NSGA-II with other objective functions. For optimization max f = -min f.

MATLAB error: “Matrix dimensions must agree” when not dealing with matrices

I am trying to find the displacement x(t) as shown but i keep on getting the error
Error using +
Matrix dimensions must agree.
My code is as shown below and its for an over damped vibration system
for i = 1 : 100;
t(i)= i/40;
x(i) = (C1*exp(-s+(((s^2)-1)^.5)*Wn*t)) + (C2*exp(-s-(((s^2)-1)^.5)*Wn*t));
end
I looked up this problem earlier and I saw a similar problem where a (.) was missing in front of the operator and tried this on my code but still couldn't get it to work. I don't know if I placed them in the wrong places or not but I am still stuck.
Could anyone please show me where I went wrong?
This is very likely because you use t inside the expression for x, and not t(i). (Assuming all other variables are scalars.
Try:
for ii = 1 : 100;
t(ii)= ii/40
x(ii) = (C1*exp(-s+(((s^2)-1)^0.5)*Wn*t(ii)))+ (C2*exp(-s-(((s^2)-1)^0.5)*Wn*t(ii)))
end
A better solution would be to vectorize this:
t = (1:100)./40;
x = (C1.*exp(-s+(((s^2)-1)^.5)*Wn.*t))+ (C2.*exp(-s-(((s^2)-1)^.5)*Wn.*t))

Sampling and DTFT in Matlab

I need to produce a signal x=-2*cos(100*pi*n)+2*cos(140*pi*n)+cos(200*pi*n)
So I put it like this :
N=1024;
for n=1:N
x=-2*cos(100*pi*n)+2*cos(140*pi*n)+cos(200*pi*n);
end
But What I get is that the result keeps giving out 1
I tried to test each values according to each n, and I get the same results for any n
For example -2*cos(100*pi*n) with n=1 has to be -1.393310473. Instead of that, Matlab gave the result -2 for it and it always gave -2 for any n
I don't know how to fix it, so I hope someone could help me out! Thank you!
Not sure where you get the idea that -2*cos(100*pi) should be anything other than -2. Maybe you are not aware that Matlab works in radians?
Look at your expression. Each term can be factored to contain 2*pi*(an integer). And you should know that cos(2*pi*(an integer)) = 1.
So the results are exactly as expected.
What you are seeing is basically what happens when you under-sample a waveform. You may know that the Nyquist criterion says that you need to have a sampling rate that is at least two times greater than the highest frequency component present; but in your case, you are sampling one point every 50, 70, 100 complete cycles. So you are "far beyond Nyquist". And that can only be solved by sampling more closely.
For example, you could do:
t = linspace(0, 1, 1024); % sample the waveform 1024 times between 0 and 1
f1 = 50;
f2 = 70;
f3 = 100;
signal = -2*cos(2*pi*f1*t) + 2*cos(2*pi*f2*t) + cos(2*pi*f3*t);
figure; plot(t, signal)
I think you are using degrees when you are doing your calculations, so do this:
n = 1:1024
x=-2*cosd(100*pi*n)+2*cosd(140*pi*n)+cosd(200*pi*n);
cosd uses degrees instead of radians. Radians is the default for cos so matlab has a separate function when degree input is used. For me this gave:
-2*cosd(100*pi*1) = -1.3933
The first term that I got using:
x=-2*cosd(100*pi*1)+2*cosd(140*pi*1)+cosd(200*pi*1)
x = -1.0693
Also notice that I defined n as n = 1:1024; this will give all integers from 1,2,...,1024,
there is no need to use a for loop since many of Matlab's built in functions are vectorized. Meaning you can just input a vector and it will calculate the function for every element in the vector.