-
Notifications
You must be signed in to change notification settings - Fork 0
/
readfile.m
117 lines (113 loc) · 2.45 KB
/
readfile.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
function [error, method, f, g, x, epsilon, max_iter] = readfile()
%{
file format:
bisection -> root finding method
x^2 + 8*x - 7 -> function
sqrt(-8*x + 7) -> G(x) (only in fixed point method)
5 9 -> bounds OR initial guess(es) depending on the method
1e06 -> epsilon
100 -> maximum number of iterations
%}
% open file
filter = {'.txt'};
[name, path] = uigetfile(filter);
directory = [path name];
if length(directory) == 2
fid = -1;
else
fid = fopen(directory);
end
% check if file exists
if (fid < 0)
error = 'You did not choose a file';
method = '';
f = '';
g = '';
x = '';
epsilon = '';
max_iter = '';
return
end
% read input data
method = fgetl(fid);
f = fgetl(fid);
if strcmp(method, 'Fixed Point')
g = fgetl(fid);
else
g = '';
end
Xin = fgetl(fid);
epsilon = fgetl(fid);
max_iter = fgetl(fid);
% close file
fclose(fid);
% validate inputs
% check for miaaing fields
if (f == -1)
error = 'F(x) is missing';
return
elseif (g == -1)
error = 'G(x) is missing';
return
elseif (Xin == -1)
error = 'Initial guess(es) are missing';
return;
end
% validate initial guess(es)
x = str2num(Xin);
switch method
case {'Fixed Point', 'Newton Raphson'}
if length(x) ~= 1
error = 'There must be exactly 1 initial guess';
return
end
case {'Bisection', 'False Position'}
if length(x) ~= 2
error = 'There must be exactly 2 initial bounds';
return
end
if x(1) >= x(2)
error = 'Upper bound must be greater than lower bound';
return
end
case 'Secant'
if length(x) ~= 2
error = 'There must be exactly 2 previous guesses';
return
end
otherwise
error = 'Invalid root finding method';
return
end
x = Xin;
% validate epsilon
if epsilon == -1
epsilon = '0.00001';
else
es = str2num(epsilon);
if length(es) ~= 1
error = 'Invalid accuracy format';
return
end
if (es < 0) || (es > 1)
error = 'Invalid accuracy format';
return
end
end
% validate max_iter
if max_iter == -1
max_iter = '50';
else
i = str2num(epsilon);
if length(i) ~= 1
error = 'Invalid number of maximum iterations';
return
end
if (i < 0) || (i > 1)
error = 'Invalid number of maximum iterations';
return
end
end
% No errors
error = 0;
end