Plotting a function within for loop
15 views (last 30 days)
Show older comments
Hello,
Im trying to plot the theta value in my file for the values of the index. How can I plot all the results on a single plot rather than have the plot only show the result for each specific iteration?
Thank you
0 Comments
Accepted Answer
David Hill
on 2 Apr 2021
function RetractionModel2
AB = 0.0732;
AD = 0.0788;
BC = 0.0585;
CD = 0.0575;
a0 = 99.4;
for i= 0:90
alpha = a0 - i;
BD = sqrt(AB^2+AD^2-2*AB*AD*cosd(alpha));
delta = asind((AB./BD).*sind(alpha));
beta = 180 - alpha - delta;
psi = acosd((BD.^2+CD^2-BC.^2)/(2*BD*CD));
zeta = asind((CD/BC)*sin(psi));
phi = beta - zeta;
theta(i+1) = delta - psi; %need to index
end
plot(0:90,theta);
end
More Answers (1)
William Rose
on 2 Apr 2021
Your function does not assign a value to the output variable "output".
I suggest you initialize vectors theta and phi inside the funciton, before the for loop. Then populate those vectors, one element at a time, during each loop pass. Then return those vectors from the function to the calling program (such as main.m). Then plot each vector in the calling program. See attached example.
%main.m
%Leandro Seguro & W.Rose
[theta,phi]=RetractionModel2;
figure;
subplot(2,1,1); plot(0:90,theta,'rx-');
title('RetractionModel2');
ylabel('Theta');
subplot(2,1,2); plot(0:90,phi,'rx-');
xlabel('i'); ylabel('Phi');
The modified function is below. Take note of what is different.
function [theta,phi] = RetractionModel2(~)
%This function returns vectors theta and phi.
AB = 0.0732;
AD = 0.0788;
BC = 0.0585;
CD = 0.0575;
a0 = 99.4;
phi=zeros(91,1); %initialize phi vector
theta=zeros(91,1); %initialize theta vector
for i= 0:1:90
alpha = a0 - i;
BD = sqrt(AB^2+AD^2-2*AB*AD*cosd(alpha));
delta = asind((AB./BD).*sind(alpha)) ;
beta = 180 - alpha - delta;
psi = acosd((BD.^2+CD^2-BC.^2)/(2*BD*CD));
zeta = asind((CD/BC)*sin(psi));
phi(i+1) = beta - zeta;
theta(i+1) = delta - psi;
end
end
Minor comment: I added semicolons to suppress the display of the intermediate results in the function.
0 Comments
See Also
Categories
Find more on Annotations 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!