2014-12-08 55 views
0

我必須做一個任務,我必須根據水的密度找到水下多少球的深度,然後我必須繪製它。我在家裏沒有matlab,但我使用八度,由於某種原因,它不是編譯,它不是說任何錯誤。這裏是我的代碼在matlab中找到一個根,不編譯

function my_script() 

% weight function 
function func = weight(x,p) 
func = p *pi* 4- 3 * pi*x ^2 + pi* x ^3; 


% make the secant method 
function root = secant(func , p, x0, x1, tol, count) 

while count ~= 0 

y1 = func(x0,p); 
y2 = func(x1, p); 
k = (x1 - x0)/(y2 - y1); 
R = y2 * k; 
root = x1 - R; 

if abs(func(root,p)) < tol 
break; 
end 

x0 = x1; 
x1 = root; 
count = count - 1; 

end 

%create array for depth values 

y_val = []; 

%input the roots into the array with a loop 

for p = 0:0.01:1 

t = secant(@weight, p, 0, 1, 0.000001, 1000000); 
disp (t); 
y_val = [y_val t]; 

end 

% create the x - axis 
x_val = 0 : 0.01 : 1; 

%plotting the graph 
figure; 
plot (x_val, y_val) 
xlabel('Density'); 
ylabel('Depth '); 
title('Floating Sphere vs Density '); 

回答

2

創建你寫的東西的另一種方法是將它分成三個不同的功能。

你不得不重功能,weight.m

% weight function 
function func = weight(x,p) 
func = p *pi* 4- 3 * pi*x ^2 + pi* x ^3; 

和割線法功能,secant.m

% make the secant method 
function root = secant(func , p, x0, x1, tol, count) 

while count ~= 0 

y1 = func(x0,p); 
y2 = func(x1, p); 
k = (x1 - x0)/(y2 - y1); 
R = y2 * k; 
root = x1 - R; 

if abs(func(root,p)) < tol 
break; 
end 

x0 = x1; 
x1 = root; 
count = count - 1; 

end 

%create array for depth values 

y_val = []; 

%input the roots into the array with a loop 

for p = 0:0.01:1 

t = secant(@weight, p, 0, 1, 0.000001, 1000000); 
disp (t); 
y_val = [y_val t]; 

end 

% create the x - axis 
x_val = 0 : 0.01 : 1; 

%plotting the graph 
figure; 
plot (x_val, y_val) 
xlabel('Density'); 
ylabel('Depth '); 
title('Floating Sphere vs Density '); 

然後你必須my_script()

function my_script() 

但它是一個空的函數,所以輸出是正確的!在定義下一個功能之前,必須完成每個功能的所有命令。

我有你想要從secant功能while環起結束拿出一切,並把它放入主my_script()功能的感覺。

2

這是您的代碼,八度風格。注意到我暫時評論了「disp(t);」聲明以避免長時間的值列表。這樣,情節立即被繪製。希望這有助於。

function my_script 

    %create array for depth values 

    y_val = []; 

    %input the roots into the array with a loop 

    for p = 0:0.01:1 
    t = secant(@weight, p, 0, 1, 0.000001, 1000000); 
    %disp (t); 
    y_val = [y_val t]; 
    endfor 

    % create the x - axis 
    x_val = 0 : 0.01 : 1; 

    %plotting the graph 
    figure(1) 
    plot (x_val, y_val) 
    xlabel('Density'); 
    ylabel('Depth '); 
    title('Floating Sphere vs Density '); 

endfunction 

% make the secant method 
function root = secant(func , p, x0, x1, tol, count) 

    while count ~= 0 

    y1 = func(x0,p); 
    y2 = func(x1, p); 
    k = (x1 - x0)/(y2 - y1); 
    R = y2 * k; 
    root = x1 - R; 

    if abs(func(root,p)) < tol 
     break; 
    end 

    x0 = x1; 
    x1 = root; 
    count = count - 1; 

    endwhile 
endfunction 

% weight function 
function func = weight(x,p) 
    func = p *pi* 4- 3 * pi*x ^2 + pi* x ^3; 
endfunction 
+0

notenote:請避免將「Stack Snippets」用於非JavaScript,CSS或HTML的內容。 – nkjt 2014-12-08 11:24:26

相關問題