Plotting a function within for loop

3 次查看(过去 30 天)
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

采纳的回答

David Hill
David Hill 2021-4-2
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

更多回答(1 个)

William Rose
William Rose 2021-4-2
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by