Write a function to calculate the cubic root of a 2D array

์กฐํšŒ ์ˆ˜: 9 (์ตœ๊ทผ 30์ผ)
Leah Taylor
Leah Taylor 2020๋…„ 3์›” 17์ผ
๋‹ต๋ณ€: Sriram Tadavarty 2020๋…„ 3์›” 17์ผ
(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

์ฑ„ํƒ๋œ ๋‹ต๋ณ€

Sriram Tadavarty
Sriram Tadavarty 2020๋…„ 3์›” 17์ผ
Hi Leah,
Update the while loop variable n to 1 within the second for loop. This is the issue with half way wrong answer. The index is not getting initialized for each element in the matrix. See the change in below code.
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; THis has to be placed within the second for loop
for rows = 1:i
for cols = 1:j
P = matrix(rows,cols);
xi = P;
n = 1; % It should start from 1 for every element.
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
Hope this heps.
Regards,
Sriram

์ถ”๊ฐ€ ๋‹ต๋ณ€ (0๊ฐœ)

์นดํ…Œ๊ณ ๋ฆฌ

Help Center ๋ฐ File Exchange์—์„œ Loops and Conditional Statements์— ๋Œ€ํ•ด ์ž์„ธํžˆ ์•Œ์•„๋ณด๊ธฐ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by