MATLAB: Error: index must be a positive integer or logical.


Hi dear friends.
I am matlab beginer and have a problem about the Error: index must be a positive integer or logical.
That I see in this part of my code.
The error is: Attempted to access Bs(0); index must be a positive integer or logical.
So I wana have a negative value in Bs(0). what should I do?
My code is:

Best Answer

You are confusing formula and indexing.
In MATLAB, except under some circumstances involving symbolic variables, every time you have () appearing after a variable on the left hand side of an assignment statement, you are doing indexing. Bs(0) is an attempt to index a variable named Bs at offset 0. That is not permitted in MATLAB: offsets must be positive integers, so 1, 2, 3, ...
In particular assigning to Bs(0) does not create a formula for Bs saying that when formula Bs is evaluated at value 0, that a particular value is to be result.
MATLAB has two basic types of objects: 1) variables that can be indexed at positive integer locations (or by logical values), and 2) formula that can be evaluated at arbitrary values (that need not even be real-valued.)
Formulas in MATLAB are called functions. When you can write them in the form of single expressions, you can create them as "handles" to "anonymous functions" and you can assign the handles to variables. For example,
F = @(x) x.^2 - 1
creates an anonymous function with formula x -> x^2-1, and assigns the handle of that function to F. After that, F(-7.2) and F(0) and F(pi) would all be valid invocations of the function handle to compute the value of the formula.
In MATLAB, you cannot define a piece by piece the way you might abstractly write y(-1) -> 5, y(0) -> -2, y(pi) -> 11, y(pi+1E-50) = -4 . There is no way in MATLAB (without writing a bunch of code yourself) to make a statement along the line of
%this section is not valid in MATLAB
Y(-1) = 5;
Y(0) = -2;
Y(pi) = 11;
Y(pi+1E-50) = -4;
to try to define a formula for Y. There are ways you can express computing this, such as
Y = @(x) (x==-1).*5 + (x==0).*-2 + (x==pi).*11 + (x==pi+1e-50).*-4
Y = piecewise(x==-1, 5, x==0, -2, x==pi, 11, x==pi+1e-50, -4) %requires symbolic toolbox
Your line of code
is creating Bs as a variable that holds 10 (double precision) values and is initialized to all 0. Variables can be indexed at positive integer locations, so Bs(1) = -(imag(yo)); would be valid, but this is not a formula.
Related Question