This is my matlab code , I got Not enough input argument error in line 2 and i don't know how to fix it. Anyhelp ? Thanks in advance .
function [] = Integr1( F,a,b )
i = ((b - a)/500);
x = a;k = 0; n = 0;
while x <= b
F1 = F(x);
x = x + i;
F2 = F(x);
m = ((F1+F2)*i)/2;
k = k +m;
end
k
x = a; e = 0; o = 0;
while x <= (b - 2*i)
x = x + i;
e = e + F(x);
x = x + i;
o = o + F(x);
end
n = (i/3)*(F(a) + F(b) + 2*o + 4*e)
This code performs integration by the trapezoidal rule. The last line of code gave it away. Please do not just push the Play button in your MATLAB editor. Don't even think about it, and ignore that it's there. Instead, go into your Command Prompt, and you need to define the inputs that go into this function. These inputs are:
F: A function you want to integrate:
a: The starting x point
b: The ending x point
BTW, your function will not do anything once you run it. You probably want to return the integral result, and so you need to modify the first line of your code to this:
function n = Integr1( F,a,b )
The last line of code assigns n to be the area under the curve, and that's what you want to return.
Now, let's define your parameters. A simple example for F is a linear function... something like:
F = #(x) 2*x + 3;
This defines a function y = 2*x + 3. Next define the starting and ending points:
a = 1; b = 4;
I made them 1 and 4 respectively. Now you can call the code:
out = Integr1(F, a, b);
out should contain the integral of y = 2*x + 3 from x = 1 to x = 4.
Related
How can I vectorize this code? At the moment it runs so slow. I'm really stuck and I've spent the last couple of hours trying to vectorize it, however I can't seem to get it to work correctly.
My naive program below works incredibly slowly. N should really be 10,000 but the program is struggling with N = 100. Any advice would be appreciated.
The code wants to iterate through the functions given N times for each value w21. It then plots the last 200 values for each value of w21. The code below does work as expected in terms of the plot but as mentioned is far to slow since for a good plot the values need to be in the thousands.
hold on
% Number of iterations
N = 100;
x = 1;
y = 1;
z = 1;
for w21 = linspace(-12,-3,N)
for i = 1:N-1
y = y_iterate(x,z,w21);
z = z_iterate(y);
x = x_iterate(y);
if i >= (N - 200)
p = plot(w21,x,'.k','MarkerSize',3);
end
end
end
Required functions:
function val = x_iterate(y)
val = -3 + 8.*(1 ./ (1 + exp(-y)));
end
function val = z_iterate(y)
val = -7 + 8.*(1 ./ (1 + exp(-y)));
end
function val = y_iterate(x,z,w21)
val = 4 + w21.*(1 ./ (1 + exp(-x))) + 6.*(1 ./ (1 + exp(-z)));
end
I believe it's because of plot. Try:
[X,Y,Z] = deal( zeros(N,N-1) );
w21 = linspace(-12,-3,N);
for i = 1:N
for j = 1:N-1
y = y_iterate(x,z,w21(i));
z = z_iterate(y);
x = x_iterate(y);
X(i,j) = x;
Y(i,j) = y;
Z(i,j) = z;
end
end
nn = max(1,N-200);
plot(w21,X(nn:end,:),'.k')
I've created a code for the Simpson's rule but I think I got the function wrong. I have no other sources to refer to (or they're too difficult to be understood). Here is my code:
function s = simpson(f_str, a, b, h)
f = inline(f_str);
n = (b-a)/h;
x = a + [1:n-1]*h;
xi = a + [1:n]*h;
s = h/3 * (f(a) + f(b) + 2*sum(f(x)) + 4*sum(f(xi)));
end
Can anybody help see where is the wrong part?
Assuming that the h in your function is the step size:
function s = simpson(f_str, a, b, h)
% The sample vector will be
xi = a:h:b;
f = inline(f_str);
% the function at the endpoints
fa = f(xi(1));
fb = f(xi(end));
% the even terms.. i.e. f(x2), f(x4), ...
feven = f(xi(3:2:end-2));
% similarly the odd terms.. i.e. f(x1), f(x3), ...
fodd = f(xi(2:2:end));
% Bringing everything together
s = h / 3 * (fa + 2 * sum(feven) + 4 * sum(fodd) + fb);
end
Source:
https://en.wikipedia.org/wiki/Simpson%27s_rule
I want to use this rational number in computations without losing the accuracy of the picture in Matlab:
f = 359.0 + 16241/16250.0
I think storing, for instance by f = uint64(359.0 + 16241/16250.0) loses accuracy, seen as 360 in Matlab.
I think the best way to handle the thing is never to store the value but to store its factors like
% f = a + b/c
a = 359
b = 16241
c = 16250
and then doing computation by the variables a, b and c, and giving the result as a picture.
Is this a good way to maintain the accuracy?
As you suggest, if you absolutely don't want to lose accuracy when storing a rational number, the best solution probably is to store the number in terms of its integer components.
Instead of your three components (f = a + b/c) you can reduce the reprentation to two components: f = n/d. Thus each rational number would be defined (and stored) as the two-component integer vector [n d]. For example, the number f in your example corresponds to n=5849991 and d=16250.
To simplify handling rational numbers stored this way, you could define a helper function which converts from the [n d] representation to n/d before applyling the desired operation:
useInteger = #(x, nd, fun) fun(x,double(nd(1))/double(nd(2)));
Then
>> x = sqrt(pi);
>> nd = int64([5849991 16250]);
>> useInteger(x, nd, #plus)
ans =
361.7719
>> useInteger(x, nd, #times)
ans =
638.0824
If you want to achieve arbitrarily high precision in computations, you should consider using variable-precision arithmetic (vpa) with string arguments. With that approach you get to specify how many digits you want:
>> vpa('sqrt(pi)*5849991/16250', 50)
ans =
638.08240465923757600307902117159072301901656248436
Perhaps create a Rational class and define the needed operations (plus,minus,times,etc.). Start with something like this:
Rational.m
classdef Rational
properties
n;
d;
end
methods
function obj = Rational(n,d)
GCD = gcd(n,d);
obj.n = n./GCD;
obj.d = d./GCD;
end
function d = dec(obj)
d = double(obj.n)/double(obj.d);
end
% X .* Y
function R = times(X,Y)
chkxy(X,Y);
if isnumeric(X),
N = X .* Y.n; D = Y.d;
elseif isnumeric(Y),
N = X.n .* Y; D = X.d;
else
N = X.n .* Y.n; D = X.d .* Y.d;
end
R = Rational(N,D);
end
% X * Y
function R = mtimes(X,Y)
R = times(X,Y);
end
% X ./ Y
function R = rdivide(X,Y)
if isnumeric(Y),
y = Rational(1,Y);
else
y = Rational(Y.d,Y.n);
end
R = times(X,y);
end
% X / Y
function R = mrdivide(X,Y)
R = rdivide(X,Y);
end
% X + Y
function R = plus(X,Y)
chkxy(X,Y);
if isnumeric(X),
N = X.*Y.d + Y.n; D = Y.d;
elseif isnumeric(Y),
N = Y.*X.d + X.n; D = X.d;
else
D = lcm(X.d,Y.d);
N = sum([X.n Y.n].*(D./[X.d Y.d]));
end
R = Rational(N,D);
end
% X - Y
function R = minus(X,Y)
R = plus(X,-Y);
end
% -X
function R = uminus(X)
R = Rational(-X.n,X.d);
end
function chkxy(X,Y)
if (~isa(X, 'Rational') && ~isnumeric(X)) || ...
(~isa(Y, 'Rational') && ~isnumeric(Y)),
error('X and Y must be Rational or numeric.');
end
end
end
end
Examples
Construct objects:
>> clear all % reset class definition
>> r1 = Rational(int64(1),int64(2))
r1 =
Rational with properties:
n: 1
d: 2
>> r2 = Rational(int64(3),int64(4))
r2 =
Rational with properties:
n: 3
d: 4
Add and subtract:
>> r1+r2
ans =
Rational with properties:
n: 5
d: 4
>> r1-r2
ans =
Rational with properties:
n: -1
d: 4
Multiply and divide:
>> r1*r2
ans =
Rational with properties:
n: 3
d: 8
>> r1/r2
ans =
Rational with properties:
n: 2
d: 3
Get decimal value:
>> r12 = r1/r2; % 2/3 ((1/2)/(3/4))
>> f = r12.dec
f =
0.6667
Extension to LuisMendo's answer
I got this as the error for your suggestion by py
>>> a = 638.08240465923757600307902117159072301901656248436059
>>> a
638.0824046592376 % do not know if Python is computing here with exact number
>>> b = 638.0824
>>> ave = abs(b+a)/2
>>> diff = abs(b-a)
>>> ave = abs(b+a)/2
>>> diff/ave
7.30193709165014e-09
which is more than the proposed error storing error above.
I run in WolframAlpha
x = sqrt(pi)
x*5849991/16250
and get
509.11609919757198016211937362635174599076143654820109
I am not sure if this is what you meant in your comment of your answer.
Extension to chappjc's answer.
I have now
[B,T,F] = tfrwv(data1, 1:length(data1), length(data1)); % here F double
fs = Rational(uint64(5849991), uint64(16250));
t = 1/fs;
imagesc(T*t, F*fs, B);
I run it
Error using .*
Integers can only be combined with integers of
the same class, or scalar doubles.
Error in .* (line 23)
N = X .* Y.n; D = Y.d;
Error in * (line 34)
R = times(X,Y);
How can you multiply in this class the double with Rational?
I'm trying to replicate the Simpson's rule by writing a function for it. However, I'm still not clear how I could possibly use eval to transform a string to a actual function in MatLab.
The function is:
function result = simpson(fun, x0, xn, n)
f = eval(fun);
h = (xn-x0)/2;
xstart = f(x0) + f(xn);
x1 = 0;
x2 = 0;
for i = 1:n-1
x = x0 + h*i;
if (mod(i,2) == 0)
x2 = x2 + f(x);
else
x1 = x1 + f(x);
end
end
result = h*(xstart + 2*x2 + 4*x1)/3;
The error reported is
Error using eval
Undefined function or variable 'x'
How could I pass x to a string form of a function?
The clean way to do that: Use a function handle, avoid eval.
Function handles are documented here: http://www.mathworks.de/de/help/matlab/ref/function_handle.html
Define them like this:
sqr = #(x) x.^2;
and then call your function:
simpson(sqr, 1, 2, 3);
within your function, you should e able to call fun(3) and get 9 as a result.
If you have to use eval, I could see two solutions:
The Sneaky way: simpson('#(x) x.^2') (eval creates a proper function handle)
The dirty way:
function result = simpson(fun)
x = 4;
f = eval(fun);
result = f;
return;
end
Call it like this: simpson('x.^2')
The problem here is the way eval is being used. The documentation indicates that in your example the output f would not be a function handle (as is expected by the way the code uses it), but rather the output of the fun function.
So, in order to make the eval function work you need to provide it with it's input.
For example:
fun = 'x.^2';
x = 4;
f = eval(fun);
Results in f == 16
In short, any time you wish to call fun you would have to set x to the appropriate value, call eval and store the result.
For example, in your code:
f = eval(fun);
h = (xn-x0)/2;
xstart = f(x0) + f(xn);
Would become:
h = (xn-x0)/2;
x = x0;
fx0 = eval(fun);
x = xn;
fxn = eval(fun);
xstart = fx0 + fxn;
I would suggest function handles as a safer and easier way of implementing this, but as mentioned in the comments this is not allowed in your case.
I'm trying to solve this system:
x = a + e(c - e*x/((x^2+y^2)^(3/2)))
y = b + c(d - e*y/((x^2+y^2)^(3/2)))
I'm using fsolve, but not matter what I put in as the starting points for the iteration, I get the answer that the starting points are the roots of the equation.
close all, clear all, clc
a = 1;
b = 2;
c = 3;
d = 4;
e = 5;
fsolve(#u1FsolveFUNC, [1,2])
Function:
function outvar = u1FsolveFUNC(invar)
global a b c d e
outvar = [...
-invar(1) + a + e*(c - e*(invar(1) / ((invar(1)^2 + invar(2)^2)^(3/2)))) ;
-invar(2) + b + e*(d - e*(invar(2) / ((invar(1)^2 + invar(2)^2)^(3/2))))]
end
I could try with [1,2] as invariables, and it will say that that is a root to the equation, alltough the correct answer for [1,2] is [12.76,15.52]
Ideas?
If you write your script like this
a = 1;
b = 2;
c = 3;
d = 4;
e = 5;
f = #(XY) [...
-XY(1) + a + e*(c - e*(XY(1) ./ (XY(1).^2 + XY(2).^2).^(3/2)))
-XY(2) + b + e*(d - e*(XY(2) ./ (XY(1).^2 + XY(2).^2).^(3/2)))];
fsolve(f, [1,2])
it is a lot clearer and cleaner. Moreover, it works :)
It works because you haven't declared a,b,c,d and e to be global before you assigned values to them. You then try to import them in your function, but at that time, they are still not defined as being global, so MATLAB thinks you just initialized a bunch of globals, setting their initial values to empty ([]).
And the solution to an empty equation is the initial value (I immediately admit, this is a bit counter-intuitive).
So this equation involves some inverse-square law...Gravity? Electrodynamics?
Note that, depending on the values of a-e, there may be multiple solutions; see this figure:
Solutions are those points [X,Y] where Z is simultaneously zero for both equations. for the values you give, there is a point like that at
[X,Y] = [15.958213798693690 13.978039302961506]
but also at
[X,Y] = [0.553696225634946 0.789264790080377]
(there's possibly even more...)
When you are using global command you have to use the command with all the variables in each function (and main workspace).
eg.
Main script
global a b c d e % Note
a = 1; b = 2; c = 3; d = 4; e = 5;
fsolve(#u1FsolveFUNC,[1,2])
Function
function outvar = u1FsolveFUNC(invar)
global a b c d e % Note
outvar = [-invar(1) + a + e*(c - e*(invar(1) / ((invar(1)^2 + invar(2)^2)^(3/2)))) ; -invar(2) + b + e*(d - e*(invar(2) / ((invar(1)^2 + invar(2)^2)^(3/2))))]