error about negative ou NA values in a array when using absolute values - function

a = 2;
epsilon = 1e-10;
t0 = 1;
N = 20;
function t = metodoDeNewton(a, t0, N, epsilon)
t = zeros(1, N+1);
t(1) = t0;
for i = 1:N
t(i+1) = t(i) - (t(i)^2 - (a - sin(t(i)))) / (2 * t(i) - cos(t(i)));
if (abs(t(i+1) - t(i)) < epsilon)
break;
endif
endfor
endfunction
t = metodoDeNewton(a, t0, N, epsilon);
% Mostra a última iteração, que é a aproximação da raiz da equação
disp(t(end));
% Estima a ordem de convergência e o coeficiente assintótico de convergência
% Para isso, calcula a razão entre duas iterações consecutivas e a razão entre
% o erro absoluto dessas iterações e o erro absoluto das iterações anteriores
r = zeros(1, length(t) - 1);
k = zeros(1, length(t) - 1);
for i = 2:length(t)
r(i-1) = t(i) / t(i-1);
k(i-1) = (abs(t(i) - t(i-1))) / (abs(t(i-1) - t(i-2)));
endfor
% Mostra a razão e o coeficiente assintótico de convergência
x = disp(r(end));
y = disp(k(end));
This code gives me the error error: t(0): subscripts must be either integers 1 to (2^63)-1 or logicals I understand this is because my k variable calculates a negative integer maybe, and I don't really understand why, since my values will allways be positive. I thought that maybe it's because the for loop might be trying to calculate NA values, but even so, how do I fix that?

Related

How do i use the second function i've created?

It's giving me an error ( value on right hand side of assignment is undefined) when i want to call the second function that i've created on line 12
function cosaprox
clc, clear
%d es el incremento y c sera la aproximacion del coseno
d = pi/100;
c = 0;
tol = 0.2;
i = 0;
flag = true;
%Aproximacion del cos
while flag
%Iteracion de la sumatoria
x=facto (2*i)
i+=1
if abs(c - cos(2*pi))>= tol
flag = false
else
endif
endwhile
disp (c)
end
function facto (x)
if x==0;
x=1;
endif
for h = 1:x-1
x = x*h;
endfor
end

Simulating waves in disc or circle form

I am getting an error when I run this code while selecting disc view or circle view option for wave simulation. The code and error are attached. I think there is some problem in this part of code typically in fzero function. Any help would be great.
Code:
function z = bjzeros(n,k)
% BJZEROS Zeros of the Bessel function.
% z = bjzeros(n,k) is the first k zeros of besselj(n,x)
% delta must be chosen so that the linear search can take
% steps as large as possible
delta = .99*pi;
Jsubn = inline('besselj(n,x)''x','n');
a = n+1;
fa = besselj(n,a);
z = zeros(1,k);
j = 0;
while j < k
b = a + delta;
fb = besselj(n,b);
if sign(fb) ~= sign(fa)
j = j+1;
z(j) = fzerotx(Jsubn,[a b],n);
end
a = b;
fa = fb;
end
Error:
Undefined function 'fzerotx' for input arguments of type 'inline'.
Error in waves>bjzeros (line 292)
z(j) = fzerotx(Jsubn,[a b],n);
Error in waves (line 137)
mu = [bjzeros(0,2) bjzeros(1,2)];
Function Declarations and Syntax
The fzerotx() function may not be declared. You can follow the file structure below to create the required M-files/functions in the same directory. Another small error may be caused by a missing comma, I got rid of the error by changing the line:
Jsubn = inline('besselj(n,x)''x','n');
to
Jsubn = inline('besselj(n,x)','x','n');
File 1: Main File/Function Call → [main.m]
mu = [bjzeros(0,2) bjzeros(1,2)];
File 2: bjzeros() Function → [bjzeros.m]
function z = bjzeros(n,k)
% BJZEROS Zeros of the Bessel function.
% z = bjzeros(n,k) is the first k zeros of besselj(n,x)
% delta must be chosen so that the linear search can take
% steps as large as possible
delta = .99*pi;
Jsubn = inline('besselj(n,x)','x','n');
a = n+1;
fa = besselj(n,a);
z = zeros(1,k);
j = 0;
while j < k
b = a + delta;
fb = besselj(n,b);
if sign(fb) ~= sign(fa)
j = j+1;
z(j) = fzerotx(Jsubn,[a b],n);
end
a = b;
fa = fb;
end
end
File 3: fzerotx() Function → [fzerotx.m]
Function Reference: MATLAB: Textbook version of FZERO
function b = fzerotx(F,ab,varargin)
%FZEROTX Textbook version of FZERO.
% x = fzerotx(F,[a,b]) tries to find a zero of F(x) between a and b.
% F(a) and F(b) must have opposite signs. fzerotx returns one
% end point of a small subinterval of [a,b] where F changes sign.
% Arguments beyond the first two, fzerotx(F,[a,b],p1,p2,...),
% are passed on, F(x,p1,p2,..).
%
% Examples:
% fzerotx(#sin,[1,4])
% F = #(x) sin(x); fzerotx(F,[1,4])
% Copyright 2014 Cleve Moler
% Copyright 2014 The MathWorks, Inc.
% Initialize.
a = ab(1);
b = ab(2);
fa = F(a,varargin{:});
fb = F(b,varargin{:});
if sign(fa) == sign(fb)
error('Function must change sign on the interval')
end
c = a;
fc = fa;
d = b - c;
e = d;
% Main loop, exit from middle of the loop
while fb ~= 0
% The three current points, a, b, and c, satisfy:
% f(x) changes sign between a and b.
% abs(f(b)) <= abs(f(a)).
% c = previous b, so c might = a.
% The next point is chosen from
% Bisection point, (a+b)/2.
% Secant point determined by b and c.
% Inverse quadratic interpolation point determined
% by a, b, and c if they are distinct.
if sign(fa) == sign(fb)
a = c; fa = fc;
d = b - c; e = d;
end
if abs(fa) < abs(fb)
c = b; b = a; a = c;
fc = fb; fb = fa; fa = fc;
end
% Convergence test and possible exit
m = 0.5*(a - b);
tol = 2.0*eps*max(abs(b),1.0);
if (abs(m) <= tol) | (fb == 0.0)
break
end
% Choose bisection or interpolation
if (abs(e) < tol) | (abs(fc) <= abs(fb))
% Bisection
d = m;
e = m;
else
% Interpolation
s = fb/fc;
if (a == c)
% Linear interpolation (secant)
p = 2.0*m*s;
q = 1.0 - s;
else
% Inverse quadratic interpolation
q = fc/fa;
r = fb/fa;
p = s*(2.0*m*q*(q - r) - (b - c)*(r - 1.0));
q = (q - 1.0)*(r - 1.0)*(s - 1.0);
end;
if p > 0, q = -q; else p = -p; end;
% Is interpolated point acceptable
if (2.0*p < 3.0*m*q - abs(tol*q)) & (p < abs(0.5*e*q))
e = d;
d = p/q;
else
d = m;
e = m;
end;
end
% Next point
c = b;
fc = fb;
if abs(d) > tol
b = b + d;
else
b = b - sign(b-a)*tol;
end
fb = F(b,varargin{:});
end
Ran using MATLAB R2019b

Implementing Euler's Method in GNU Octave

I am reading "Numerical Methods for Engineers" by Chapra and Canale. In it, they've provided pseudocode for the implementation of Euler's method (for solving ordinary differential equations). Here is the pseucode:
Pseucode for implementing Euler's method
I tried implementing this code in GNU Octave, but depending on the input values, I am getting one of two errors:
The program doesn't give any output at all. I have to press 'Ctrl + C' in order to break execution.
The program gives this message:
error: 'ynew' undefined near line 5 column 21
error: called from
Integrator at line 5 column 9
main at line 18 column 7
I would be very grateful if you could get this program to work for me. I am actually an amateur in GNU Octave. Thank you.
Edit 1: Here is my code. For main.m:
%prompt user
y = input('Initial value of y:');
xi = input('Initial value of x:');
xf = input('Final value of x:');
dx = input('Step size:');
xout = input('Output interval:');
x = xi;
m = 0;
xpm = x;
ypm = y;
while(1)
xend = x + xout;
if xend > xf
xend = xf;
h = dx;
Integrator(x,y,h,xend);
m = m + 1;
xpm = x;
ypm = y;
if x >= xf
break;
endif
endif
end
For Integrator.m:
function Integrator(x,y,h,xend)
while(1)
if xend - x < h
h = xend - x;
Euler(x,y,h,ynew);
y = ynew;
if x >= xend
break;
endif
endif
end
endfunction
For Euler.m:
function Euler(x,y,h,ynew)
Derivs(x,y,dydx);
ynew = y + dydx * h;
x = x + h;
endfunction
For Derivs.m:
function Derivs(x,y,dydx)
dydx = -2 * x^3 + 12 * x^2 - 20 * x + 8.5;
endfunction
Edit 2: I shoud mention that the differential equation which Chapra and Canale have given as an example is:
y'(x) = -2 * x^3 + 12 * x^2 - 20 * x + 8.5
That is why the 'Derivs.m' script shows dydx to be this particular polynomial.
Here is my final code. It has four different M-files:
main.m
%prompt the user
y = input('Initial value of y:');
x = input('Initial value of x:');
xf = input('Final value of x:');
dx = input('Step size:');
xout = dx;
%boring calculations
m = 1;
xp = [x];
yp = [y];
while x < xf
[x,y] = Integrator(x,y,dx,min(xf, x+xout));
m = m+1;
xp(m) = x;
yp(m) = y;
end
%plot the final result
plot(xp,yp);
title('Solution using Euler Method');
ylabel('Dependent variable (y)');
xlabel('Independent variable (x)');
grid on;
Integrator.m
%This function takes in 4 inputs (x,y,h,xend) and returns 2 outputs [x,y]
function [x,y] = Integrator(x,y,h,xend)
while x < xend
h = min(h, xend-x);
[x,y] = Euler(x,y,h);
end
endfunction
Euler.m
%This function takes in 3 inputs (x,y,h) and returns 2 outputs [x,ynew]
function [x,ynew] = Euler(x,y,h)
dydx = Derivs(x,y);
ynew = y + dydx * h;
x = x + h;
endfunction
Derivs.m
%This function takes in 2 inputs (x,y) and returns 1 output [dydx]
function [dydx] = Derivs(x,y)
dydx = -2 * x^3 + 12 * x^2 - 20 * x + 8.5;
endfunction
Your functions should look like
function [x, y] = Integrator(x,y,h,xend)
while x < xend
h = min(h, xend-x)
[x,y] = Euler(x,y,h);
end%while
end%function
as an example. Depending on what you want to do with the result, your main loop might need to collect all the results from the single steps. One variant for that is
m = 1;
xp = [x];
yp = [y];
while x < xf
[x,y] = Integrator(x,y,dx,min(xf, x+xout));
m = m+1;
xp(m) = x;
yp(m) = y;
end%while

Octave - Call to m file and variables

I have condition.m, and it has inside it a loop that calculates the condition number of a user asked matrix:
if(p == 1)
for i = 1:co
for j = 1:li
somacolunas(j) = somacolunas(j) + A(j,i);
end
end
for i = 1:co
for j = 1:li
somacolunasinvA(j) = somacolunasinvA(j) + abs(invA)(j,i);
end
end
% encontrar o valor máximo
maxco = somacolunas(1);
for i = 1:length(somacolunas)
if somacolunas(i) > maxco
maxco = somacolunas(i);
end
end
maxcoinv = somacolunasinvA(1);
for y = 1:length(somacolunasinvA)
if somacolunasinvA(y) > maxcoinv
maxcoinv = somacolunasinvA(y);
end
end
printf('o número de condição segundo a norma 1 é: %3.2f\n', maxco * maxcoinv);
I want to call the condition.m file inside another m.file (that is in the same directory) and make use of the output vars (maxco and maxcoinv) to do some other math.
I know that i can do condition; inside the other m file to access the condition.m file. But how to get access to it's variables, and if i need pass values to condition.m for loop iterate?
Any ideas for the best method?

Function guards & 'where' syntax in Haskell

I am trying to Learn Me a Haskell, and I decided to practice by writing a simple function for inverting 3x3 matrices. It should be easy, yet nothing I try will compile successfully.
Here is my code:
matInv3x3 :: [[Double]] -> [[Double]]
matInv3x3 m
| length m /= 3 = error "wrong number of rows"
| length (m !! 0) /= 3 = error "wrong number of elements in row 0"
| length (m !! 1) /= 3 = error "wrong number of elements in row 1"
| length (m !! 2) /= 3 = error "wrong number of elements in row 2"
| det == 0 = error "zero determinant"
| otherwise = mInv
where a = m !! 0 !! 0
b = m !! 0 !! 1
c = m !! 0 !! 2
d = m !! 1 !! 0
e = m !! 1 !! 1
f = m !! 1 !! 2
g = m !! 2 !! 0
h = m !! 2 !! 1
i = m !! 2 !! 2
det = a*(e*i - f*h) - b*(i*d - f*g) + c*(d*h - e*g)
A = (e*i - f*h) / det
B = -(d*i - f*g) / det
C = (d*h - e*g) / det
D = -(b*i - c*h) / det
E = (a*i - c*g) / det
F = -(a*h - b*g) / det
G = (b*f - c*e) / det
H = -(a*f - c*d) / det
I = (a*e - b*d) / det
mInv = [[A,B,C],[D,E,F],[G,H,I]]
I am trying to guard against everything which can go wrong: bad list dimensions, and zero determinant. I modeled it after examples in the 'Learn You A...' book. I am trying to rely on the lazy evaluation in case the matrix has zero determinant.
GHCi won't compile it, citing a parse error for the '=' on line 10 (where b is defined). I'm sure there is some simple, fundamental thing I am missing. Can someone point out what I did wrong?
UPDATE:
I implemented the fixes proposed in the comments, and also corrected the swapped indices mistake I made (didn't spot it before, as the code wouldn't compile). Here is the fixed code, which inverts 3x3 matrices correctly:
matInv3x3 :: [[Double]] -> [[Double]]
matInv3x3 m
| length m /= 3 = error "wrong number of rows"
| length (m !! 0) /= 3 = error "wrong number of elements in row 0"
| length (m !! 1) /= 3 = error "wrong number of elements in row 1"
| length (m !! 2) /= 3 = error "wrong number of elements in row 2"
| abs det < 1.0e-15 = error "zero or near-zero determinant"
| otherwise = mInv
where [[a,d,g],[b,e,h],[c,f,i]] = m
det = a*(e*i - f*h) - b*(i*d - f*g) + c*(d*h - e*g)
a' = (e*i - f*h) / det
b' = -(d*i - f*g) / det
c' = (d*h - e*g) / det
d' = -(b*i - c*h) / det
e' = (a*i - c*g) / det
f' = -(a*h - b*g) / det
g' = (b*f - c*e) / det
h' = -(a*f - c*d) / det
i' = (a*e - b*d) / det
mInv = [[a',b',c'],[d',e',f'],[g',h',i']]
A good exercise would be to generalize this function to arbitrary nxn matrices. Here is one way to calculate the determinant of an nxn as a start in case you are interested.
-- Remove the nth element from a list
remove :: Int -> [a] -> [a]
remove n xs = ys ++ (tail zs)
where
(ys, zs) = splitAt n xs
-- Minor matrix of cofactor C(i,j)
minor :: Int -> Int -> [[a]] -> [[a]]
minor i j xs = remove j $ map (remove i) xs
-- The determinant of a square matrix represented as a list of lists
-- representing column vectors, that is [column].
det :: Num a => [[a]] -> a
det (a:[]) = head a
det m = sum [(-1)^i * (c1 !! i) * det (minor i 0 m) | i <- [0 .. (n-1)]]
where
c1 = head m
n = length m