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 visualización (últimos 30 días)
Mostrar comentarios más antiguos
0 comentarios
Respuestas (2)
Walter Roberson
el 15 de Jul. de 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
0 comentarios
Steven Lord
el 15 de Jul. de 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)
Of course, if you're using a release that supports implicit expansion you don't need the loop.
y2 = x .* a
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.
0 comentarios
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!