Write a function to calculate the cubic root of a 2D array
Ältere Kommentare anzeigen
(This is a homework question, so I'm not supposed to use nthroot except to check my answer).
An algorithm for calculating the cubic root of a number, 3√? , starts by choosing a value ?1 as a first estimate of the root. Using this value, a second, more accurate value ?2 is calculated as ?2 = ?1 (?1^3 + 2?)/(2?1^3 + ?), which is then used for calculating a third, still more accurate value ?3, and so on. The general equation for calculating the ? + 1 value from the ? ?ℎ value of ? is ??+1 = ?? (??^3 + 2?)/(2??^3 + ?).
I am supposed to be writing a function using two for loops and a while loop to calculate the cube root of a 2D array. My function so far will work for the first few numbers of a matrix, but "gives up" halfway through and gives incorrect answers. Can anyone tell me why this is happening? (The equation in the while loop is given to us, and I double checked it already, and E is for the error).
F = [1:5; 10:-1:6; 11:15]
function [Root3] = HW7P2_fn(matrix)
% Function to determine cubic root of a number
% Input value is the number whose cubic root is needed
% Output value is the cubic root
clc
[i, j] = size(matrix);
Root3 = zeros(i,j);
n = 1;
for rows = 1:i
for cols = 1:j
P = matrix(rows,cols);
xi = P;
while n <= 50
xip1 = (xi*(xi^3 + 2*P))/(2*(xi^3) + P);
Root3(rows,cols) = xip1;
E = abs((xip1 - xi)/xi);
if E < 10e-10
break
end
xi = xip1;
n = n+1;
end
end
end
end
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Platform and License finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!