In an assignment A(I) = B, the number of elements in B and I must be the same

29 views (last 30 days)
hi,
I am facing problem with this code:
function P = legendre(x,n)
P(1) = 1;
P(2) = x;
P(3) = (3*(x^2)- 1)/2;
P(n+1) =((2*(n+1))* x *(P(n)) - n*(P(n-1)))/(n+1);
end
Ans Test_bech is:
clear legendre;
x = -1;
a = 5;
len = length(x);
P = zeros (1,len);
for i = 3:a
P(n+1) = legendre(x,i);
end
when I run this test script. it will show this error:
In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in lendre_tb (line 11)
P(n+1) = legendre(x,3);
please help me out this!!
  3 Comments
Mikhail
Mikhail on 16 Oct 2014
The easiest way to eliminate this type of error - use debug mode. Set breakpoint at the line where error occurs, and before evaluating this line in debug mode check size() of left and right hand sizes.

Sign in to comment.

Answers (1)

the cyclist
the cyclist on 16 Oct 2014
The specific reason you are getting this error is that the output of your legendre function is a vector, but in the line
P(n+1) = LP(x,i);
you are assigning that vector output to a single element of P.
  3 Comments
Guillaume
Guillaume on 17 Oct 2014
Regardless of the size of P, if n is scalar,
P(n+1)
is a scalar, i.e. a single number. You're trying to stuff a vector, i.e. several numbers in there. No matter how you try, it's not going to fit. You either need to change your legendre function to return a single number or put the output into more than one number.
Varinder
Varinder on 17 Oct 2014
dear, now I am getting this error
Attempted to access P(4); index out of bounds because numel(P)=3.
Error in legendre (line 5) P(n+1) =((2*(n+1))* x (P(n)) - n(P(n-1)))/(n+1);
Error in new_tb (line 7)
i just modified my test script
clear legendre;
x = -1;
n=5;
P = zeros (1,n);
for i = 3:n
[P] =legendre(x,i);
end

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!