我希望我的泰勒方法能夠在執行時的功能提示。我試着用input(prompt)作爲MATLAB文檔中的說明。問題是,它會提示我每次遇到代碼時都要輸入函數。MATLAB獲取函數的輸入只有一次
function taylorMethod(a, b, h, alpha, order)
f = @(t, y) input('Enter f(t, y): ');
fPrime = @(t, y) input('Enter f''(t, y): ');
taylor2 = @(t, w) f(t, w) + h/2*fPrime(t, w);
if order > 2
f2Prime = @(t, y) input('Enter f''''(t, y): ');
taylor3 = @(t, w) taylor2(t, w) + h^2/factorial(3)*f2Prime(t, w);
if order == 4
f3Prime = @(t, y) input('Enter f''''''(t, y): ');
taylor4 = @(t, w) taylor3(t, w) + h^3/factorial(4)*f3Prime(t, w);
end
end
function res = t(i)
if i == a
res = a;
return;
end
res = h + t(i - 1);
end
idx = a;
for i = a:h:b
fprintf('i = %d; t_i = %.2f; w(i) = %.10f\n', idx, t(idx), w(idx));
idx = idx + 1;
end
function res = w(i)
j = i - 1;
if i == a
res = alpha;
return;
end
if order == 2
res = w(j) + h*taylor2(t(j), w(j));
elseif order == 3
res = w(j) + h*taylor3(t(j), w(j));
elseif order == 4
res = w(j) + h*taylor4(t(j), w(j));
end
return;
end
end
我也試圖在用戶輸入存儲在像這樣的字符串:
fString = input('Enter f(t, y): ', 's');
fPrimeString = input('Enter f''(t, y): ', 's');
f = @(t, y) fString;
fPrime = @(t, y) fPrimeString;
taylor2 = @(t, w) f(t, w) + h/2*fPrime(t, w);
但我得到了一個錯誤:
Error using + Matrix dimensions must agree.
Error in taylorMethod>@(t,w)f(t,w)+h/2*fPrime(t,w) (line 13) taylor2 = @(t, w) f(t, w) + h/2*fPrime(t, w);
Error in taylorMethod/w (line 47) res = w(j) + h*taylor2(t(j), w(j));
Error in taylorMethod (line 35) fprintf('i = %d; t_i = %.2f; w(i) = %.10f\n', idx, t(idx), w(idx));
的原因,我沒有通過功能作爲參數,是因爲我要使用不同的順序相同的代碼...和不同的訂單不會有相同數量的所需要的功能。
有沒有辦法,我可以提示用戶一次的功能,並使用功能,可不必再提示的方法嗎?