Store values from while loop into an array
Mostrar comentarios más antiguos
I'm writing a function that will calculate the distance between two vectors. When trying to store the values from each iteration of the while loop into an array, I'm getting an "Index exceeds the number of array elements (2)." error message. Here's the code:
function [distvect,theta] = calcDistAngle(u,v)
if (length(u) == length(v) && iscolumn(u) == 1 && iscolumn(v) == 1)
n=0;
c = zeros(length(u), 1);
while n <= length(u)
n = n+1;
c(n) = (u(n)-v(n))^2;
end
distvect = sqrt(sum(c(n)));
theta = acos((dot(u,v))/(norm(u)*norm(v)));
else
distvect = -1;
theta = -1;
end
end
Thanks in advance for the help
1 comentario
jannat alsaidi
el 2 de Abr. de 2021
did you mean by (the values from each iteration ) you want to store answer of c in an array? array with what size?
Respuesta aceptada
Más respuestas (1)
You're testing that n<=length(u), but then you immediately increment it. You'd need to adjust your test limit.
Better yet, avoid while loops if you already know the number of iterations you need. It's more concise, and there are fewer things to go wrong.
% iscolumn already returns a logical
if (length(u) == length(v) && iscolumn(u) && iscolumn(v))
c = zeros(length(u), 1);
for n=1:length(u)
c(n) = (u(n)-v(n))^2;
end
distvect = sqrt(sum(c)); % you probably want to find the 2-norm of the whole thing
theta = acos((dot(u,v))/(norm(u)*norm(v)));
else
distvect = -1;
theta = -1;
end
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!