I can't find what's wrong with my code

조회 수: 1 (최근 30일)
연진 소
연진 소 2023년 5월 24일
답변: Diwakar Diwakar 2023년 5월 24일
I tried to plot the graph showing relationship between r and c, but the c shows the single value, not the pair with r.
I couldn't find what's the problem... please help:(
Here's my code:
clc
clear
clf
close all
%input data
D_AB=1.5e-07;
D=0.1;
t=5058.85;
n=5;
c=0.02;
y=0;
%because as n increases, series goes to 0->do not need to calculate a
r=0.01:0.01:0.05
for k=1:n
hold on;
y=y+((-1)^k)*D*sin(2*k*pi*r/D)*exp(-(4*D_AB*(pi^2)*(k^2)*t/D^2))/(pi*r*k);
c=(y+1)*(-0.02)+0.02;
plot(r,c)
end
hold off;

답변 (3개)

KSSV
KSSV 2023년 5월 24일
As you are doing a single point at time, you need to use the marker '.'.
%input data
D_AB=1.5e-07;
D=0.1;
t=5058.85;
n=5;
c=0.02;
y=0;
%because as n increases, series goes to 0->do not need to calculate a
r=0.01:0.01:0.05 ;
figure
hold on
for k=1:n
y=y+((-1)^k)*D*sin(2*k*pi*r/D)*exp(-(4*D_AB*(pi^2)*(k^2)*t/D^2))/(pi*r*k);
c=(y+1)*(-0.02)+0.02;
plot(r,c,'.r')
end
hold off;

VBBV
VBBV 2023년 5월 24일
편집: VBBV 2023년 5월 24일
clc
clear
close all
%input data
D_AB=1.5e-07;
D=0.1;
t=5058.85;
n=5;
c=0.02;
y=0;
%because as n increases, series goes to 0->do not need to calculate a
r=0.01:0.01:0.05;
hold on;
for k=1:n
% --------------------------->>--------------------------------->>
y=y+((-1)^k)*D*sin(2*k*pi*r/D).*exp(-(4*D_AB*(pi^2)*(k^2)*t./D^2))./(pi*r*k);
c=(y+1)*(-0.02)+0.02;
plot(r,c,'linewidth',2); grid
xlabel('r');ylabel('c')
end
Use element wise division & multiplication for the below line
y=y+((-1)^k)*D*sin(2*k*pi*r/D).*exp(-(4*D_AB*(pi^2)*(k^2)*t./D^2))./(pi*r*k);

Diwakar Diwakar
Diwakar Diwakar 2023년 5월 24일
It seems that you're attempting to plot a graph showing the relationship between r and c. However, based on the code you provided, it appears that the c value is being updated within the loop, resulting in a single value rather than a pair with r. To resolve this issue, you can store the values of r and c in separate arrays within the loop, and then plot the graph outside the loop using the collected values. Here's the modified code:
D_AB = 1.5e-07;
D = 0.1;
t = 5058.85;
n = 5;
c = 0.02;
y = 0;
r = 0.01:0.01:0.05;
c_values = zeros(size(r)); % Array to store c values
for k = 1:n
hold on;
y = y + ((-1)^k) * D * sin(2 * k * pi * r / D) * exp(-(4 * D_AB * (pi^2) * (k^2) * t / D^2)) / (pi * r * k);
c_values = (y + 1) * (-0.02) + 0.02; % Store c values in the array
end
plot(r, c_values); % Plot the graph with r and c_values
hold off;

카테고리

Help CenterFile Exchange에서 Graphics Performance에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by