Matlab Writing function for rectangle - function

I have a homework, where I need to create a function in matlab which plots a rectangle. We can't use a rectangle function. We must define a own function.
I already coded some parts:
M=[1 2
1 6
4 6
4 2];
x1= M(1,1);
x2= M(2,1);
x3= M(3,1);
x4= M(4,1);
y1= M(1,2);
y2= M(2,2);
y3= M(3,2);
y4= M(4,2);
x= [x1 x2 x3 x4 x1];
y= [y1 y2 y3 y4 y1];
function plotrec = prec(x,y)
plot(x,y,'g-o');
axis([0 10 0 10])
end
But the function doesn't work.
Thanks!

It looks like you've already figured out what you needed, but in any case perhaps you will find this approach to the function to be helpful.
function plot_rec(M)
xmin = min(M(:,1))-1;
xmax = max(M(:,1))+1;
ymin = min(M(:,2))-1;
ymax = max(M(:,2))+1;
M = [M; M(1,:)];
plot(M(:,1),M(:,2),'g-o')
axis([xmin xmax ymin ymax])
end

Related

Octave, The secant method

I am trying to implement the secant method using Octave, and in particular I made a function called secant("function","x0","x1","tolerance"). I used the while-loop for calculate the root of a function and I think the problem is in the loop.
But the result that I get, it is not what I expect. The correct answer is x=0,49438.
My code is the following:
tol = 10.^(-5); # tolerance
x0 = 0.4; # initial point
x1 = 0.6; # initial point
syms x;
fun = #(x) exp(sin(x)) - 2/(1+x.^2); # f(x) = exp(sin(x)) - 2/(1+x^2)
fprintf("Function f(x)\n");
fun
fprintf("\n");
fprintf("initial points: %f\n",x0,x1);
function[raiz,errel,niter] = secant(fun,x0,x1,tol)
niter = 0; # steps number
errel = []; # the vector of relative errors
y0 = fun(x0); # f(x0)
y1 = fun(x1); # f(x1)
ra = 0.0; # ra is the variable of the function's root
while abs(ra-x1)>= tol
niter += 1;
ra = x1 - ((x1-x0)./(y1-y0)).*y0; # formula of the secant method
if abs((ra-x1))<tol
raiz = ra;
return;
endif
x0 = x1; y0 = y1; x1 = ra;
y1 = fun(ra);
errel(niter) = abs(ra-x1)/abs(ra); # Calcule of relative error
endwhile
if abs((ra-x1)/ra)<tol
fprintf ('The method is over\n');
fprintf ('\n');
endif
raiz = ra;
endfunction
[r,er,tot] = secant(fun,x0,x1,tol)
I appreciate the help you can give me
It makes little sense to use the secant root in the loop condition. At first it is not defined, and inside the loop it is shifted into the support points for the next secant. Note that at the end ra and x1 contain the same value, making the loop condition trivial, in a wrong way.
Next, the secant has the equation
y(x) = y1 + (y1-y0)/(x1-x0)*(x-x_1)
check that with this formula y(x0)=y0 and y(x1)=y1. Thus the secant root is to be found at
x = x1 - (x1-x0)/(y1-y0)*y1
Finally, at no point are symbolic expressions used, defining x as symbolic variable is superfluous.
The break-out test inside the loop is also redundant and prevents a coherent state after the loop. Just remove it and remember that x1 contains the last approximation.
With all this I get an execution log as follows:
Function f(x)
fun =
#(x) exp (sin (x)) - 2 / (1 + x .^ 2)
initial points: 0.400000
initial points: 0.600000
The method is over
r = 0.494379048216965
er =
2.182723270633349e-01 3.747373180587413e-03 5.220701832080676e-05 1.899377363987941e-08
tot = 4

Calling Octave interpolation function within function body

I'm trying to wrap Octave interpolation function in a function body,
function FUN = inter(p);
FUN = interpn (x1, x2, x3, x4, x5, A, p(1), p(2), p(3), p(4), p(5), "spline");
end
The reason why I'm doing this is because I'm using a package which function needs a string name function which would be in this case packageFunction("inter", argument1);
The issue is calling now for instance like,
disp("value = "), inter([10 2 4 3 4])
doesn't work; Doesn't see the vectors error: 'x1' undefined ,
Of course the vectors xi and matrix A are defined above the function body. Would appreciate advice on this,
thanks, Damir
------------- in file example1.m
[a b c] = fminuit('gaussian','mnplot',[10 166 33],[x;y;dy])
------------- in file gaussian.m
function f = gaussian(par,data);
%theoretical function
f = par(1)/(sqrt(2*pi)*par(3)) * exp(-.5*((data(1,:)-
par(2))./par(3)).^2);
if (size(data,1)==2), %chi-square, error = 1
f = sum((data(2,:) - f).^2);
elseif (size(data,1)>2), %chi-square, error = 3rd row of data
f = sum(((data(2,:) - f)./data(3,:)).^2);
end
Given you are using an old function that requires a string as the function, the first solution below will not work. This is, however, the right way to do it. Changing the old function to use function handles instead of strings would be my preferred solution. However, you can also use an alternative solution further down below, which uses global variables. This is not the recommended approach (we should strive to avoid globals), but will solve your near-term problems.
Correct approach: use an anonymous function
You should use an anonymous function, these can capture variables when they're defined:
inter = #(p)interpn (x1, x2, x3, x4, x5, A, p(1), p(2), p(3), p(4), p(5), "spline");
Now inter(p) works just as if inter had been declared as a normal function. But the values of x1, x2, etc as they were defined when inter was defined will be stored inside inter.
As stated, the function you pass inter to must be written to accept function handles.
Bad, quick solution: use global variables
First, create a file inter.m with the following contents:
function FUN = inter(p);
global x1 x2 x3 x4 x5 A
FUN = interpn (x1, x2, x3, x4, x5, A, p(1), p(2), p(3), p(4), p(5), "spline");
end
Next, in your function of script that calls inter, again declare the global variables (currently MATLAB warns that you should declare them as globals before giving them a value, in future versions this will be required):
global x1 x2 x3 x4 x5 A
x1 = ...
x2 = ...
% etc
inter([10 2 4 3 4])
% or:
fminuit('inter',...)

Scilab plotting functions with if

I have a problen in scilab
How can I plot functions containing if and < like
function y = alpha(t)
if (t < 227.8) then
y = 0.75;
elseif (t < 300) then
y = 2.8 - 0.009 .* t;
else
y = 0.1;
end
endfunction
and
function [r]=minus_alpha(t)
r = 1 - alpha(t)
endfunction
When I use
x = linspace(0,300)
plot(x, alpha(x))
I got the error message
WARNING: Transposing row vector X to get compatible dimensions
plot2d: falsche Größe für Eingangsargument: inkompatible Größen.
Error 999 : in plot2d called by plot
Sorry for german mix. Thank you.
You can avoid explicit loop and be more efficient using the followin code
function y = alpha(t)
y=0.1*ones(t);
y(t<227.8)=0.75;
i=t>=227.8&t<300;
y(i)=2.8 - 0.009 .* t(i);
endfunction
It is really sad to see a great majority of Scilab community is not aware of vectorized operations. You can change your function to:
function y = alpha(t)
y = 0.1;
if t < 227.8 then
y = 0.75;
elseif t < 300 then
y = 2.8 - 0.009 * t;
end
y = 1 - y;
endfunction
and then use feval to broadcast the function over the sequence:
x = linspace(0, 300);
plot2d(x, feval(x, alpha));
which results:
rule of thumb if you are using for loop you need to revise your code and if someone is offering you a code where there is unnecessary for loop you shouldn't probably use it.
All the proposed answers are overcomplicated considering that the function alpha in the original demand is piecewise-affine. In Scilab in can be coded that way:
x = linspace(0,400,1000);
plot(x,linear_interpn(x,[227.8 300],[0.75 0.1]))
i.e. you just have to know the nodes coordinates (here abscissae) and value of the function at nodes. The function linear_interpn does also multilinear interpolation, it is worth knowing it guys...
If you check the output of your alpha(x), you will see that it is just a scalar (not a vector). I guess you wanted something like this, so it's necessary to iterate through t to compute each value of y based on the value of t:
clc;
clear;
function y = alpha(t)
for i=1:size(t,"*")
if t(i) < 227.8 then
y(i) = 0.75;
elseif t(i) < 300 then
y(i) = 2.8 - 0.009 * t(i);
else
y(i) = 0.1;
end
end
endfunction
x = linspace(0,300);
plot2d(x,alpha(x));
If you find the answer useful, please do not forget to accept it, so others will see that your problem is solved.
Before your answers (thank you) my workaround was a combination of indicator functions composed with floor and exp( -t^2):
function y = alpha(t)
y = floor(exp(-(t .* (t-T1)) / (T1*T1))) * 0.75
+ floor(exp(-((t-T2) .* (t- T1) / (2000)))) .* (2.8-0.009 .* t)
+ floor(exp(-((t-T2) .* (t-1000) / (200000))))*0.1
endfunction

(SAS 9.4) Is any functions in SAS which can extract residual from regression equation?

I need help to know a function can extract residual from regression equation.
I need that function to make 2-stage credit model. I want to extract a residual from first stage model(regression) and apply the residual to second stage model(y value).
It will be very helpful if there is proper function in SAS 9.4.
thank you
Look at the documentation around PROC REG.
proc reg data=inData;
model y = x1 x2 x3;
output out=ouData r=resid;
run;
quit;
This takes data from the INDATA data set, regresses Y on X1, X2, and X3, and outputs the residuals in OUTDATA.
If you want to get fancy, you can do it 2-stage least squares with proc model.
proc model data=have;
exo x1 x2 x3;
endo y1 y2;
y1 = b1 + b2*y2 + b3*x1 + b4*x2;
y2 = b5 + b6*y1 + b7*x3;
fit y1 y2 / 2sls;
instruments _exog_;
run;

Use the same plot for different subfunctions

I am calling a functions recursively and I want them all to draw in the same plot. When i try to create a handler and pass it on with the parameters I get the following error:
??? Error using ==> set Invalid handle object.
Error in ==> triangle at 23
set(h, 'xdata', [x1,x3], 'ydata', [y1,y3]);
Before calling my function I've created a handler and set my preferences:
h = plot([0,1],[0,0]);
set(h, 'erasemode', 'none');
triangle(0,0,1,0,10,0,h)
This is my function:
function triangle(x1,y1,x2,y2, deepth , n,h)
%Paints a equilateral triangle for two given Points
if depth > n
shg
clf reset
%vector
v_12 = [x2-x1;y2-y1];
%rotate vector
g_uz = [0.5,-sqrt(3)/2;sqrt(3)/2, 0.5];
p = g_uz * v_12;
x3 = p(1) + x1;
y3 = p(2) + y1;
axis([-10 10 -10 10]);
axis off
drawnow
set(h, 'xdata', [x1,x3], 'ydata', [y1,y3]);
drawnow
set(h, 'xdata', [x2,x3], 'ydata', [y2,y3]);
drawnow
v_13 = [x3-x1,y3-y1];
v_23 = [x3-x2,y3-y2];
% 1-3 triangle
triangle(x1+v_13(1)/3,y1 + v_13(1)/3, x1+ 2*v_13(1)/3,y1 + 2*v_13(1)/3, tiefe, n+1 );
end
Do you know any solutions? How can I Plot in an object form a function i called?
The clf on line 6 clears the figure, removing the line that you want to use as your graphic output.
Remove that line and see if it works.
Try using hold all. It lets you plot new lines in the figure without clearing existing lines.
figure
hold all
triangle(...)
Inside your function just call plot.
plot(x, y)
plot(x, z)