Array indices must be positive integers or logical values.
1 view (last 30 days)
Show older comments
Aurick Das
on 12 May 2019
Answered: Sulaymon Eshkabilov
on 12 May 2019
xa=2
xb=3
ya=.9093
yb=.1411
x=0:1:6
for x=0:1:6
y(x)=((x-xb)/(xa-xb))*ya-((x-xa)/(xa-xb))*yb
end
plot(y,x)
why this code is showing "Array indices must be positive integers or logical values." this statement?
0 Comments
Accepted Answer
madhan ravi
on 12 May 2019
Edited: madhan ravi
on 12 May 2019
Because indexing starts from one https://matlab.fandom.com/wiki/FAQ#How_do_I_fix_the_error_.22Subscript_indices_must_either_be_real_positive_integers_or_logicals..22.3F :
No loop is needed here:
y=((x-xb)/(xa-xb))*ya-((x-xa)/(xa-xb))*yb;
plot(y,x)
0 Comments
More Answers (2)
Image Analyst
on 12 May 2019
It's a FAQ so see the FAQ for complete info: Click here for the FAQ
In short, you can't start with x(0) since 0 is not an allowed array index. Try this:
xa=2
xb=3
ya=.9093
yb=.1411
x=0:1:6
for k = 1 : length(x)
thisX = x(k)
y(k)=((thisX-xb)/(xa-xb))*ya-((thisX-xa)/(xa-xb))*yb
end
plot(x, y, 'b*-', 'LineWIdth', 2, 'MarkerSize', 15)
grid on;
0 Comments
Sulaymon Eshkabilov
on 12 May 2019
Hi,
Indeed, the indices in your case (x) have to be integers, like, 1,2,3,... can NOT be 0, -1, -2, 1.2, 2.5, etc. Index indicates the order (sequence) of the elements to be taken for processing/calculation/etc.
Here is an easy fix your problem:
xa=2;
xb=3;
ya=.9093;
yb=.1411;
x=0:1:6;
y = zeros(1, numel(x)); % Memory allocation to speed up the process that is helpful if your computation space is large.
for ii=1:numel(x)-1 % -1 needed since x starts at 0. The step = 1 (x=0:1:6) and thus, we can skip it (by default the step size is 1).
y(ii)=((x(ii)-xb)/(xa-xb))*ya-((x(ii)-xa)/(xa-xb))*yb;
end
plot(y,x), shg
Good luck
0 Comments
See Also
Categories
Find more on Introduction to Installation and Licensing 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!