Store values from while loop into an array
显示 更早的评论
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 个评论
jannat alsaidi
2021-4-2
did you mean by (the values from each iteration ) you want to store answer of c in an array? array with what size?
采纳的回答
更多回答(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
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!