2017-08-28 196 views
-2

我想知道如何將此代碼從Matlab轉換爲R代碼。看來這是中點法的代碼。任何幫助將不勝感激。將matlab代碼轉換爲R代碼

% Usage: [y t] = midpoint(f,a,b,ya,n) or y = midpoint(f,a,b,ya,n) 
% Midpoint method for initial value problems 
% 
% Input: 
% f - Matlab inline function f(t,y) 
% a,b - interval 
% ya - initial condition 
% n - number of subintervals (panels) 
% 
% Output: 
% y - computed solution 
% t - time steps 
% 
% Examples: 
% [y t]=midpoint(@myfunc,0,1,1,10);   here 'myfunc' is a user-defined function in M-file 
% y=midpoint(inline('sin(y*t)','t','y'),0,1,1,10); 
% f=inline('sin(y(1))-cos(y(2))','t','y'); 
% y=midpoint(f,0,1,1,10); 

function [y t] = midpoint(f,a,b,ya,n) 
h = (b - a)/n; 
halfh = h/2; 
y(1,:) = ya; 
t(1) = a; 
for i = 1 : n 
    t(i+1) = t(i) + h; 
    z = y(i,:) + halfh * f(t(i),y(i,:)); 
    y(i+1,:) = y(i,:) + h * f(t(i)+halfh,z); 
end; 

我有歐拉方法將R代碼是

euler <- function(f, h = 1e-7, x0, y0, xfinal) { 
         N = (xfinal - x0)/h 
         x = y = numeric(N + 1) 
         x[1] = x0; y[1] = y0 
         i = 1 
         while (i <= N) { 
         x[i + 1] = x[i] + h 
         y[i + 1] = y[i] + h * f(x[i], y[i]) 
         i = i + 1 
               } 
         return (data.frame(X = x, Y = y)) 
             } 

所以基於該matlab代碼,是否需要改變歐拉法(R代碼)H與(b - 一)/n將歐拉代碼修改爲中點法?

+0

@Sardar烏薩馬,我想修改歐拉代碼到中點方法。我在R中添加了歐拉代碼。我在Matlab中找到了一個用於中點方法的代碼,因此我正在尋找將其轉換爲R的方法。 – david

+1

中點方法屬於更廣泛的龍格庫塔方法類。看看'deSolve'軟件包。 'rkMethod'的參考以及其中一個小插曲演示瞭如何定義一個應用中點方法的函數:https://cran.r-project.org/web/packages/deSolve/index.html –

回答

3

廣義地講,我同意表達意見;不過,我決定投這個問題。 (現在刪除)這是由於matconv的存在促進了這個過程。

回答

鑑於你的代碼,我們可以通過以下方式使用matconv

pacman::p_load(matconv) 
out <- mat2r(inMat = "input.m") 

創建的out對象將嘗試翻譯Matlab代碼爲R,但是,這項工作還遠沒有結束。如果你檢查out對象,你會發現它需要進一步的工作。簡單的語句通常可以用Matlab註釋%替換爲#等等來正確翻譯,但更復雜的語句可能需要更詳細的調查。然後,您可以檢查各線,並試圖對其進行評估,看看那裏可能需要進一步的工作,例如:

eval(parse(text=out$rCode[1])) 
NULL 

(第一行是註釋,以便輸出爲NULL)

+0

注意你回答的問題早已被問過了。 https://stackoverflow.com/questions/5527145/convert-matlab-code-to-r https://stackoverflow.com/questions/12246309/how-to-convert-matlab-scripts-in-r因此,它可能最好在那裏回答。但是請注意,這樣的問題是相當偏離主題的。 – m7913d

+0

@感謝您的評論。它是否正確? input.m =函數[y t] =中點(f,a,b,ya,n)h =(b-a)/ n; halfh = h/2; y(1,:) = ya; t(1)= a; 對於i = 1:n t(i + 1)= t(i)+ h; y(i,:) + halfh * f(t(i),y(i,:)); y(i + 1,:) = y(i,:) + h * f(t(i)+ halfh,z); 結束; out < - mat2r(inMat =「input.m」) – david

+0

@david'input.m'是你的Matlab代碼文件。轉換的代碼將在'out $ rCode [n]'中提供,'n'代表每個轉換後的行。正如我在答覆中提到的,更復雜的陳述可能無法完美地翻譯。 – Konrad