Clear Filters
Clear Filters

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

2 views (last 30 days)
연진 소
연진 소 on 24 May 2023
Answered: Diwakar Diwakar on 24 May 2023
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;

Answers (3)

KSSV
KSSV on 24 May 2023
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 on 24 May 2023
Edited: VBBV on 24 May 2023
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 on 24 May 2023
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;

Tags

Community Treasure Hunt

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

Start Hunting!