Info

# How do I pass values in and out of a function, which was a script that I have converted into a function?

1 view (last 30 days)
Steve on 29 Oct 2019
Closed: MATLAB Answer Bot on 20 Aug 2021
Below is some code that I need to first convert into a function. Then I would like to write a small external for loop that passes the value of "pt" (pt = 1 : 953) into the function and then retrieves the values for ThetaInDegress_a, ThetaInDegress_b, & ThetaInDegress_c for each pt:
close all;
clearvars;
xy = F_points';
pt = 299; % choose a point in xy and we'll find the n nearest neighbors.
% Euclidean distance between xy(p,:) and all other points
dist = sqrt((xy(:,1)-xy(pt,1)).^2 + (xy(:,2)-xy(pt,2)).^2);
n = 3; % Find the n closest values (excluding the point selected)
[~, ascendIdx] = sort(dist);
ascendIdx(ascendIdx==pt) = []; %remove the pt point
xyNearest = xy(ascendIdx(1:n),:);
% dist_a = sqrt((fpep(pt,1)-fpep(pt,7)).^2 + (fpep(pt,2)-fpep(pt,8)).^2);
% dist_b = sqrt((fpep(pt,3)-fpep(pt,7)).^2 + (fpep(pt,4)-fpep(pt,8)).^2);
% dist_c = sqrt((fpep(pt,5)-fpep(pt,7)).^2 + (fpep(pt,6)-fpep(pt,8)).^2);
bdirector_x = ([fpep(pt,3) - fpep(pt,7)]);
bdirector_y = ([fpep(pt,4) - fpep(pt,8)]);
cdirector_x = ([fpep(pt,5) - fpep(pt,7)]);
cdirector_y = ([fpep(pt,6) - fpep(pt,8)]);
vector_b = [bdirector_x bdirector_y];
vector_c = [cdirector_x cdirector_y];
chordx = ([xyNearest(:,1) - xy(pt,1)]);
chordy = ([xyNearest(:,2) - xy(pt,2)]);
chordxy = [chordx chordy];
% chord_dist = sqrt((chordx).^2 + (chordy).^2);
% bdirector_dist = sqrt((bdirector_x).^2 + (bdirector_y).^2);
% cdirector_dist = sqrt((cdirector_x).^2 + (cdirector_y).^2);
for j = 1 : n
CosTheta_a(j) = dot(vector_a,chordxy(j,:))/(norm(vector_a)*norm(chordxy(j,:)));
CosTheta_b(j) = dot(vector_b,chordxy(j,:))/(norm(vector_b)*norm(chordxy(j,:)));
CosTheta_c(j) = dot(vector_c,chordxy(j,:))/(norm(vector_c)*norm(chordxy(j,:)));
end
ThetaInDegrees_a = acosd(CosTheta_a);
ThetaInDegrees_b = acosd(CosTheta_b);
ThetaInDegrees_c = acosd(CosTheta_c);
% Plot
figure()
for ii = 1 : length(chordx)
xvals = [xy(pt,2),xy(pt,2)+chordy(ii)];
yvals = [xy(pt,1),xy(pt,1)+chordx(ii)];
plot(xvals,yvals,'r-')
hold on
end
plot(xy(:,2),xy(:,1),'b.')
hold on
% Show the selected point
plot(xy(pt,2),xy(pt,1),'b.','MarkerFaceColor', 'y')
% Show nearest 'n' dots
plot(xyNearest(:,2),xyNearest(:,1),'ro')
plot(fpep(:,2),fpep(:,1),'k.')
plot(fpep(:,4),fpep(:,3),'k.')
plot(fpep(:,6),fpep(:,5),'k.')
axis equal

R2019a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!