MATLAB Answers

Hi, I keep getting index in position 2 is invalid. Array indices must be positive integers with an error in line 8 but I can’t figure it out . Can anyone please help thanks

1 view (last 30 days)

Answers (2)

Walter Roberson
Walter Roberson on 15 Jul 2021
for a=0.1:0.3
Remember that the default increment is 1 so that is 0.1:1:0.3 which is just 0.1 since the next value 0.1+1 would exceed 0.3
So you are looping and a will be assigned 0.1
y(:,a)=x*a;
But a is 0.1 so you are trying to assign to y(:,0.1). That is not a valid subscript.
You should learn this pattern
a_values = 0.1:0.3;
num_a = numel(a_values);
y = zeros(length(x), num_a) ;
for a_index = 1 : num_a
a = a_values(a_index);
y(:, a_index) = x*a;
end

Steven Lord
Steven Lord on 15 Jul 2021
There's no such thing as the 0.1st column of a matrix in MATLAB. You could use integers to index both into a vector a and a matrix y:
x = (1:10).';
a = 0.1:0.1:0.3;
% Allocate a matrix large enough to hold the computations I'm about to
% perform
y = zeros(numel(x), numel(a));
for whichA = 1:numel(a)
y(:, whichA) = x * a(whichA);
end
disp(y)
0.1000 0.2000 0.3000 0.2000 0.4000 0.6000 0.3000 0.6000 0.9000 0.4000 0.8000 1.2000 0.5000 1.0000 1.5000 0.6000 1.2000 1.8000 0.7000 1.4000 2.1000 0.8000 1.6000 2.4000 0.9000 1.8000 2.7000 1.0000 2.0000 3.0000
Of course, if you're using a release that supports implicit expansion you don't need the loop.
y2 = x .* a
y2 = 10×3
0.1000 0.2000 0.3000 0.2000 0.4000 0.6000 0.3000 0.6000 0.9000 0.4000 0.8000 1.2000 0.5000 1.0000 1.5000 0.6000 1.2000 1.8000 0.7000 1.4000 2.1000 0.8000 1.6000 2.4000 0.9000 1.8000 2.7000 1.0000 2.0000 3.0000
You're going to encounter problems later in the code as well with the subplot calls. The inputs to subplot using the syntax you're using need to be positive integer values. Finally, on line 6 the identifier line already has a meaning in MATLAB. You might want to choose a different variable name.

Community Treasure Hunt

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

Start Hunting!

Translated by