how to collect variables in an aray in for loop?
Show older comments
function close_point(p0,p1,p2,p3)
for t=0:0.1:1
b0=(1-t).^2;
b1=2*t.*(1-t);
b2=t.^2;
x=b0*p0(1)+b1*p1(1)+b2*p2(1);
y=b0*p0(2)+b1*p1(2)+b2*p2(2);
xs=sqrt((p3(1)-x).^2+(p3(2)-y).^2)
end
i want to save xs values in a array.plz tell me how to save or put xs values in array?
Accepted Answer
More Answers (2)
KSSV
on 22 May 2018
function xs = close_point(p0,p1,p2,p3)
t=0:0.1:1 ;
xs = zeros(length(t),1) ;
for i = 1:length(t)
b0=(1-t(i)).^2;
b1=2*t(i).*(1-t(i));
b2=t(i).^2;
x=b0*p0(1)+b1*p1(1)+b2*p2(1);
y=b0*p0(2)+b1*p1(2)+b2*p2(2);
xs(i)=sqrt((p3(1)-x).^2+(p3(2)-y).^2) ;
end
Just use indexing with a preallocated variable:
function out = close_point(p0,p1,p2,p3)
vec = 0:0.1:1;
out = nan(size(vec));
for k = 1:numel(vec);
t = vec(k);
b0=(1-t).^2;
b1=2*t.*(1-t);
b2=t.^2;
x=b0*p0(1)+b1*p1(1)+b2*p2(1);
y=b0*p0(2)+b1*p1(2)+b2*p2(2);
out(k) = sqrt((p3(1)-x).^2+(p3(2)-y).^2);
end
end
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!