Matlab Question Error! Index dimension error.
1 view (last 30 days)
The error occurs at the loop - while, giving me the error "Index exceeds matrix dimension"
function result = my_sqrt(x,q)
% This function uses a for loop to approximate the square root of a number
% and compare to the built in sqrt function in matlab.
% Variable declaration & Initialization
x = input('Enter a value for x: ');
q = input('Enter a value for q: ');
t = 5;
n = 1;
y(n) = (1/t).*x(n).^2
x(n+1) = ((x(n)/8)*(15-y(n)*(10-(3*y(n)))))
n = n+1;
Ben11 on 29 Jul 2014
That's because x(n+1) is undefined when you enter the while loop. From what you posted x is a single digit and not a vector, so trying to access x(2) generates the error. Also is 'x' the number you want to calculate the root of and q the precision you want?
Also t seems to be undefined is that a mistake?
Joseph Cheng on 29 Jul 2014
Edited: Joseph Cheng on 29 Jul 2014
So just as Ben11 did state x(n+1) is undefined when you first attempt the while loop. In the initialization of the function there is no x(2) defined. Without a x(2) defined you cannot do x(2)-x(1) and check if it is <=q. On a side note i believe that your while loop condition should be >=q as you want to probably loop while the square root approximation is greater than the convergence threshold.
to remedy this you could also initialize a x(2) which is x(1)+q+1 which would be replaced by the stated square root approximation you have there. (I did not check the legitimacy of your equation though).
Patrik Ek on 29 Jul 2014
Edited: Patrik Ek on 31 Jul 2014
There are a number of issues with this piece of code.
1) You should not have a clc inside a function. It is bad practice since the user may not want to clear the command window.
2) You have x and q as arguments already so you do not need the input. My advice would be to remove the inputs and either define x and q outside the function or assign them directly in the function call (in in the command window), like xSqrt = my_sqrt(3,0.01).
3) result is not defined. Also, you only need the current x and the previous, my advice would then be to define a new variable xNext and update it. Then either return xNext, update x and return x or define result = x (or xNext depending on when it is updated).
4) The algorithm that you use seems to be unstable. Read on wikipedia about methods for square root calculations. There they also advices in how to select the initial condition.
This should work fine:
function [result,n] = my_sqrt(x2,q)
% result = sqrt(x2)
% q - tolerance;
% Initial guess only a dummy for now. Check the article to improve the
x = 3;
% Counts the number of iterations, not necessary, but good now for testing
n = 1;
quitLoop = false;
xNext = 0.5*(x+x2/x);
quitLoop = true;
n = n+1;
x = xNext;
result = xNext;
where x2 is defined as the number that you want to calculate the root of. The algorithm uses newton-raphson and have a fast convergence.