How to generate plot

조회 수: 4 (최근 30일)
Kristine
Kristine 2022년 7월 24일
편집: Torsten 2022년 7월 24일
I am trying to generate a plot with K1 in the y axis and x in the x axis. My code will pull up a figure but it doesn't plot along the points. Any tips?

채택된 답변

Voss
Voss 2022년 7월 24일
Original code (with disps removed):
K1 = 0;
a = 5;
n = 30;
P0 = 100;
c = 3;
for i = 1:30
s = cos(((2*i-1)*pi)/(2*n));
x = s*a;
P = P0*(exp((-0.5)*(x/c)^2))*(1-(x/c)^2);
K1 = K1+(sqrt(pi*a)*(1/n)*P*(1+s));
figure(1)
plot(x,K1)
grid
title('K1 as a function of crack length')
end
You're plotting 30 lines, but each line contains only one point and the lines don't have any data marker. A single point with no marker doesn't show up. Also, each line replaces the previous line plotted.
To fix these things, you could include a data marker in your plot calls and call hold on to keep all the lines:
K1 = 0;
a = 5;
n = 30;
P0 = 100;
c = 3;
for i = 1:30
s = cos(((2*i-1)*pi)/(2*n));
x = s*a;
P = P0*(exp((-0.5)*(x/c)^2))*(1-(x/c)^2);
K1 = K1+(sqrt(pi*a)*(1/n)*P*(1+s));
figure(1)
plot(x,K1,'.') % '.' data marker
hold on % use hold on to preserve existing lines
grid
title('K1 as a function of crack length')
end
However, it's better (and I imagine more like what's intended) to do a vectorized calculation for x and K1 and plot them all at once:
% K1 = 0; % no longer needed
a = 5;
n = 30;
P0 = 100;
c = 3;
i = 1:30;
s = cos(((2*i-1)*pi)/(2*n));
x = s*a;
P = P0*(exp((-0.5)*(x/c).^2)).*(1-(x/c).^2); % use element-wise operations (.*, .^) to calculate all values at once
K1 = cumsum(sqrt(pi*a)*(1/n)*P.*(1+s)); % use cumsum (cumulative sum) to add the sequence of K1 values
figure() % (making a new figure this time)
plot(x,K1) % no data marker (but you could still use one if you want)
grid
title('K1 as a function of crack length')

추가 답변 (1개)

Torsten
Torsten 2022년 7월 24일
편집: Torsten 2022년 7월 24일
a = 5;
n = 30;
P0 = 100;
c = 3;
s = cos((2*(1:n)-1)*pi/(2*n));
x = a*s;
P = P0*exp(-0.5*(x/c).^2).*(1-x/c).^2;
K1 = sqrt(pi*a)/n*cumsum(P.*(1+s));
plot(x,K1)
grid
title('K1 as function of crack length')
  댓글 수: 2
Voss
Voss 2022년 7월 24일
Note that you have:
(1-x/c).^2
But OP's code has:
(1-(x/c)^2)
(Things like this is why it's better for OPs to share code as text rather than an image.)
Torsten
Torsten 2022년 7월 24일
편집: Torsten 2022년 7월 24일
(Things like this is why it's better for OPs to share code as text rather than an image.)
The main reason is to get an answer at all ...

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Audio I/O and Waveform Generation에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by