Plotting a function within for loop

조회 수: 3 (최근 30일)
Leandro Seguro
Leandro Seguro 2021년 4월 2일
답변: William Rose 2021년 4월 2일
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