How to generate plot
1 view (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Voss
on 24 Jul 2022
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')
0 Comments
More Answers (1)
Torsten
on 24 Jul 2022
Edited: Torsten
on 24 Jul 2022
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 Comments
Voss
on 24 Jul 2022
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.)
See Also
Categories
Find more on Stress and Strain 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!