How to generate plot

1 回表示 (過去 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 Center および File ExchangeStress and Strain についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by