Array indices must be positive integers or logical values.
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I am trying to make a step model for my peristaltic pump, but in line 6 i get the error: 'Array indices must be positive integers or logical values.'. I have looked it up and it says that that means that there is a variable created in my workspace that overshadows a function. But I have no idea what that means.
n = 0
x = [0:1:60]
m = length(x)
td = 5
while n<=m
if x(n) == 0
h(n) = 0
n = n+1;
elseif rem(x(n), 2*td) ==0
h(n) = h(n-1)+0
n = n+1;
elseif rem(x(n), 2*td) ~=0
h(n) = h(n-1)+l
n = n+1;
end
end
1 commentaire
Réponses (1)
Jan
le 26 Fév 2019
Modifié(e) : Jan
le 26 Fév 2019
The problem is exactly what the error message says (and not a variable shadowing a built-in function):
n = 0
...
while n <= m
if x(n) == 0
Now you try to access x(0), but indices start at 1 in Matlab. 0 is not "a positive integer". Maybe all you want is to start with
n = 1;
A for loop might be simpler:
x = 0:60; % No [] needed: 0:60 is the vector already
td = 5;
h = zeros(1, length(x)); % Pre-allocate
for n = 1:length(x)
if x(n) == 0
% h(n) = 0; % Is initialized as 0 already
elseif rem(x(n), 2*td) == 0
h(n) = h(n-1); % "+0" is a waste of reading and processing time
else % No other possibility than: if rem(x(n), 2*td) ~=0
h(n) = h(n-1) + 1; % It was: "+ l", lowercase L - is this wanted?!
end
end
Or simpler:
x = 0:60;
td = 5;
h = cumsum(rem(x, 2 * td) ~= 0);
0 commentaires
Voir également
Catégories
En savoir plus sur Multidimensional Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!